CachingRouter.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Lukas Reschke <lukas@statuscode.ch>
  7. * @author Morris Jobke <hey@morrisjobke.de>
  8. * @author Robin Appelman <robin@icewind.nl>
  9. *
  10. * @license AGPL-3.0
  11. *
  12. * This code is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU Affero General Public License, version 3,
  14. * as published by the Free Software Foundation.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU Affero General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Affero General Public License, version 3,
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>
  23. *
  24. */
  25. namespace OC\Route;
  26. use OCP\Diagnostics\IEventLogger;
  27. use OCP\ICache;
  28. use OCP\ICacheFactory;
  29. use OCP\IConfig;
  30. use OCP\IRequest;
  31. use Psr\Container\ContainerInterface;
  32. use Psr\Log\LoggerInterface;
  33. class CachingRouter extends Router {
  34. protected ICache $cache;
  35. public function __construct(
  36. ICacheFactory $cacheFactory,
  37. LoggerInterface $logger,
  38. IRequest $request,
  39. IConfig $config,
  40. IEventLogger $eventLogger,
  41. ContainerInterface $container
  42. ) {
  43. $this->cache = $cacheFactory->createLocal('route');
  44. parent::__construct($logger, $request, $config, $eventLogger, $container);
  45. }
  46. /**
  47. * Generate url based on $name and $parameters
  48. *
  49. * @param string $name Name of the route to use.
  50. * @param array $parameters Parameters for the route
  51. * @param bool $absolute
  52. * @return string
  53. */
  54. public function generate($name, $parameters = [], $absolute = false) {
  55. asort($parameters);
  56. $key = $this->context->getHost() . '#' . $this->context->getBaseUrl() . $name . sha1(json_encode($parameters)) . (int)$absolute;
  57. $cachedKey = $this->cache->get($key);
  58. if ($cachedKey) {
  59. return $cachedKey;
  60. } else {
  61. $url = parent::generate($name, $parameters, $absolute);
  62. if ($url) {
  63. $this->cache->set($key, $url, 3600);
  64. }
  65. return $url;
  66. }
  67. }
  68. }