vendor/sulu/sulu/src/Sulu/Component/Cache/Memoize.php line 77

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of Sulu.
  4. *
  5. * (c) Sulu GmbH
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace Sulu\Component\Cache;
  11. use Doctrine\Common\Cache\CacheProvider;
  12. use Symfony\Contracts\Service\ResetInterface;
  13. /**
  14. * Memoizer which uses Doctrine Cache to save data.
  15. */
  16. class Memoize implements MemoizeInterface, ResetInterface
  17. {
  18. /**
  19. * @var CacheProvider
  20. */
  21. protected $cache;
  22. /**
  23. * @var int
  24. */
  25. protected $defaultLifeTime;
  26. /**
  27. * Constructor.
  28. */
  29. public function __construct(CacheProvider $cache, $defaultLifeTime)
  30. {
  31. $this->cache = $cache;
  32. $this->defaultLifeTime = $defaultLifeTime;
  33. }
  34. public function memoize($compute, $lifeTime = null)
  35. {
  36. // used to get information of the caller
  37. // returns a callstack (0 is current function, 1 is caller function)
  38. $callers = \debug_backtrace();
  39. if (
  40. !isset($callers[1])
  41. || !isset($callers[1]['class'])
  42. || !isset($callers[1]['function'])
  43. || !isset($callers[1]['args'])
  44. ) {
  45. throw new \InvalidArgumentException();
  46. }
  47. // build cache key
  48. $id = \sprintf('%s::%s', $callers[1]['class'], $callers[1]['function']);
  49. return $this->memoizeById($id, $callers[1]['args'], $compute, $lifeTime);
  50. }
  51. public function memoizeById($id, $arguments, $compute, $lifeTime = null)
  52. {
  53. // determine lifetime
  54. if (null === $lifeTime) {
  55. $lifeTime = $this->defaultLifeTime;
  56. }
  57. // determine cache key
  58. $id = \md5(\sprintf('%s(%s)', $id, \serialize($arguments)));
  59. // memoize pattern: save result for arguments once and
  60. // return the value from cache if it is called more than once
  61. if ($this->cache->contains($id)) {
  62. return $this->cache->fetch($id);
  63. } else {
  64. $value = \call_user_func_array($compute, $arguments);
  65. $this->cache->save($id, $value, $lifeTime);
  66. return $value;
  67. }
  68. }
  69. /**
  70. * @return void
  71. */
  72. public function reset()
  73. {
  74. $this->cache->flushAll();
  75. }
  76. }