EarlyExpirationMessage.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Cache\Messenger;
  11. use Symfony\Component\Cache\Adapter\AdapterInterface;
  12. use Symfony\Component\Cache\CacheItem;
  13. use Symfony\Component\DependencyInjection\ReverseContainer;
  14. /**
  15. * Conveys a cached value that needs to be computed.
  16. */
  17. final class EarlyExpirationMessage
  18. {
  19. private $item;
  20. private $pool;
  21. private $callback;
  22. public static function create(ReverseContainer $reverseContainer, callable $callback, CacheItem $item, AdapterInterface $pool): ?self
  23. {
  24. try {
  25. $item = clone $item;
  26. $item->set(null);
  27. } catch (\Exception $e) {
  28. return null;
  29. }
  30. $pool = $reverseContainer->getId($pool);
  31. if (\is_object($callback)) {
  32. if (null === $id = $reverseContainer->getId($callback)) {
  33. return null;
  34. }
  35. $callback = '@'.$id;
  36. } elseif (!\is_array($callback)) {
  37. $callback = (string) $callback;
  38. } elseif (!\is_object($callback[0])) {
  39. $callback = [(string) $callback[0], (string) $callback[1]];
  40. } else {
  41. if (null === $id = $reverseContainer->getId($callback[0])) {
  42. return null;
  43. }
  44. $callback = ['@'.$id, (string) $callback[1]];
  45. }
  46. return new self($item, $pool, $callback);
  47. }
  48. public function getItem(): CacheItem
  49. {
  50. return $this->item;
  51. }
  52. public function getPool(): string
  53. {
  54. return $this->pool;
  55. }
  56. public function getCallback()
  57. {
  58. return $this->callback;
  59. }
  60. public function findPool(ReverseContainer $reverseContainer): AdapterInterface
  61. {
  62. return $reverseContainer->getService($this->pool);
  63. }
  64. public function findCallback(ReverseContainer $reverseContainer): callable
  65. {
  66. if (\is_string($callback = $this->callback)) {
  67. return '@' === $callback[0] ? $reverseContainer->getService(substr($callback, 1)) : $callback;
  68. }
  69. if ('@' === $callback[0][0]) {
  70. $callback[0] = $reverseContainer->getService(substr($callback[0], 1));
  71. }
  72. return $callback;
  73. }
  74. private function __construct(CacheItem $item, string $pool, $callback)
  75. {
  76. $this->item = $item;
  77. $this->pool = $pool;
  78. $this->callback = $callback;
  79. }
  80. }