1
0

CachingRouter.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Route;
  8. use OCP\App\IAppManager;
  9. use OCP\Diagnostics\IEventLogger;
  10. use OCP\ICache;
  11. use OCP\ICacheFactory;
  12. use OCP\IConfig;
  13. use OCP\IRequest;
  14. use Psr\Container\ContainerInterface;
  15. use Psr\Log\LoggerInterface;
  16. class CachingRouter extends Router {
  17. protected ICache $cache;
  18. public function __construct(
  19. ICacheFactory $cacheFactory,
  20. LoggerInterface $logger,
  21. IRequest $request,
  22. IConfig $config,
  23. IEventLogger $eventLogger,
  24. ContainerInterface $container,
  25. IAppManager $appManager,
  26. ) {
  27. $this->cache = $cacheFactory->createLocal('route');
  28. parent::__construct($logger, $request, $config, $eventLogger, $container, $appManager);
  29. }
  30. /**
  31. * Generate url based on $name and $parameters
  32. *
  33. * @param string $name Name of the route to use.
  34. * @param array $parameters Parameters for the route
  35. * @param bool $absolute
  36. * @return string
  37. */
  38. public function generate($name, $parameters = [], $absolute = false) {
  39. asort($parameters);
  40. $key = $this->context->getHost() . '#' . $this->context->getBaseUrl() . $name . sha1(json_encode($parameters)) . (int)$absolute;
  41. $cachedKey = $this->cache->get($key);
  42. if ($cachedKey) {
  43. return $cachedKey;
  44. } else {
  45. $url = parent::generate($name, $parameters, $absolute);
  46. if ($url) {
  47. $this->cache->set($key, $url, 3600);
  48. }
  49. return $url;
  50. }
  51. }
  52. }