EarlyExpirationDispatcher.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 Psr\Log\LoggerInterface;
  12. use Symfony\Component\Cache\Adapter\AdapterInterface;
  13. use Symfony\Component\Cache\CacheItem;
  14. use Symfony\Component\DependencyInjection\ReverseContainer;
  15. use Symfony\Component\Messenger\MessageBusInterface;
  16. use Symfony\Component\Messenger\Stamp\HandledStamp;
  17. /**
  18. * Sends the computation of cached values to a message bus.
  19. */
  20. class EarlyExpirationDispatcher
  21. {
  22. private $bus;
  23. private $reverseContainer;
  24. private $callbackWrapper;
  25. public function __construct(MessageBusInterface $bus, ReverseContainer $reverseContainer, ?callable $callbackWrapper = null)
  26. {
  27. $this->bus = $bus;
  28. $this->reverseContainer = $reverseContainer;
  29. $this->callbackWrapper = $callbackWrapper;
  30. }
  31. public function __invoke(callable $callback, CacheItem $item, bool &$save, AdapterInterface $pool, \Closure $setMetadata, ?LoggerInterface $logger = null)
  32. {
  33. if (!$item->isHit() || null === $message = EarlyExpirationMessage::create($this->reverseContainer, $callback, $item, $pool)) {
  34. // The item is stale or the callback cannot be reversed: we must compute the value now
  35. $logger && $logger->info('Computing item "{key}" online: '.($item->isHit() ? 'callback cannot be reversed' : 'item is stale'), ['key' => $item->getKey()]);
  36. return null !== $this->callbackWrapper ? ($this->callbackWrapper)($callback, $item, $save, $pool, $setMetadata, $logger) : $callback($item, $save);
  37. }
  38. $envelope = $this->bus->dispatch($message);
  39. if ($logger) {
  40. if ($envelope->last(HandledStamp::class)) {
  41. $logger->info('Item "{key}" was computed online', ['key' => $item->getKey()]);
  42. } else {
  43. $logger->info('Item "{key}" sent for recomputation', ['key' => $item->getKey()]);
  44. }
  45. }
  46. // The item's value is not stale, no need to write it to the backend
  47. $save = false;
  48. return $message->getItem()->get() ?? $item->get();
  49. }
  50. }