CachingRouter.php 1.8 KB

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