CachingRouter.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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\App\IAppManager;
  27. use OCP\Diagnostics\IEventLogger;
  28. use OCP\ICache;
  29. use OCP\ICacheFactory;
  30. use OCP\IConfig;
  31. use OCP\IRequest;
  32. use Psr\Container\ContainerInterface;
  33. use Psr\Log\LoggerInterface;
  34. class CachingRouter extends Router {
  35. protected ICache $cache;
  36. public function __construct(
  37. ICacheFactory $cacheFactory,
  38. LoggerInterface $logger,
  39. IRequest $request,
  40. IConfig $config,
  41. IEventLogger $eventLogger,
  42. ContainerInterface $container,
  43. IAppManager $appManager,
  44. ) {
  45. $this->cache = $cacheFactory->createLocal('route');
  46. parent::__construct($logger, $request, $config, $eventLogger, $container, $appManager);
  47. }
  48. /**
  49. * Generate url based on $name and $parameters
  50. *
  51. * @param string $name Name of the route to use.
  52. * @param array $parameters Parameters for the route
  53. * @param bool $absolute
  54. * @return string
  55. */
  56. public function generate($name, $parameters = [], $absolute = false) {
  57. asort($parameters);
  58. $key = $this->context->getHost() . '#' . $this->context->getBaseUrl() . $name . sha1(json_encode($parameters)) . (int)$absolute;
  59. $cachedKey = $this->cache->get($key);
  60. if ($cachedKey) {
  61. return $cachedKey;
  62. } else {
  63. $url = parent::generate($name, $parameters, $absolute);
  64. if ($url) {
  65. $this->cache->set($key, $url, 3600);
  66. }
  67. return $url;
  68. }
  69. }
  70. }