EarlyExpirationMessage.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 string $pool;
  21. private string|array $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. /**
  57. * @return string|string[]
  58. */
  59. public function getCallback(): string|array
  60. {
  61. return $this->callback;
  62. }
  63. public function findPool(ReverseContainer $reverseContainer): AdapterInterface
  64. {
  65. return $reverseContainer->getService($this->pool);
  66. }
  67. public function findCallback(ReverseContainer $reverseContainer): callable
  68. {
  69. if (\is_string($callback = $this->callback)) {
  70. return '@' === $callback[0] ? $reverseContainer->getService(substr($callback, 1)) : $callback;
  71. }
  72. if ('@' === $callback[0][0]) {
  73. $callback[0] = $reverseContainer->getService(substr($callback[0], 1));
  74. }
  75. return $callback;
  76. }
  77. private function __construct(CacheItem $item, string $pool, string|array $callback)
  78. {
  79. $this->item = $item;
  80. $this->pool = $pool;
  81. $this->callback = $callback;
  82. }
  83. }