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

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\Cache;
  12. use Doctrine\Common\Cache\FlushableCache;
  13. use Symfony\Contracts\Service\ResetInterface;
  14. /**
  15. * Memoizer which uses Doctrine Cache to save data.
  16. */
  17. class Memoize implements MemoizeInterface, ResetInterface
  18. {
  19. /**
  20. * @param Cache $cache should also include FlushableCache to reset in other runtimes like FrankenPHP correctly
  21. * @param int $defaultLifeTime
  22. */
  23. public function __construct(protected Cache $cache, protected $defaultLifeTime)
  24. {
  25. }
  26. public function memoize($compute, $lifeTime = null)
  27. {
  28. // used to get information of the caller
  29. // returns a callstack (0 is current function, 1 is caller function)
  30. $callers = \debug_backtrace();
  31. if (
  32. !isset($callers[1])
  33. || !isset($callers[1]['class'])
  34. || !isset($callers[1]['function'])
  35. || !isset($callers[1]['args'])
  36. ) {
  37. throw new \InvalidArgumentException();
  38. }
  39. // build cache key
  40. $id = \sprintf('%s::%s', $callers[1]['class'], $callers[1]['function']);
  41. return $this->memoizeById($id, $callers[1]['args'], $compute, $lifeTime);
  42. }
  43. public function memoizeById($id, $arguments, $compute, $lifeTime = null)
  44. {
  45. // determine lifetime
  46. if (null === $lifeTime) {
  47. $lifeTime = $this->defaultLifeTime;
  48. }
  49. // determine cache key
  50. $id = \md5(\sprintf('%s(%s)', $id, \serialize($arguments)));
  51. // memoize pattern: save result for arguments once and
  52. // return the value from cache if it is called more than once
  53. if ($this->cache->contains($id)) {
  54. return $this->cache->fetch($id);
  55. } else {
  56. $value = \call_user_func_array($compute, $arguments);
  57. $this->cache->save($id, $value, $lifeTime);
  58. return $value;
  59. }
  60. }
  61. /**
  62. * @return void
  63. */
  64. public function reset()
  65. {
  66. if ($this->cache instanceof FlushableCache) {
  67. $this->cache->flushAll();
  68. }
  69. }
  70. }