EarlyExpirationDispatcher.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 ?\Closure $callbackWrapper;
  23. public function __construct(
  24. private MessageBusInterface $bus,
  25. private ReverseContainer $reverseContainer,
  26. ?callable $callbackWrapper = null,
  27. ) {
  28. $this->callbackWrapper = null === $callbackWrapper ? null : $callbackWrapper(...);
  29. }
  30. public function __invoke(callable $callback, CacheItem $item, bool &$save, AdapterInterface $pool, \Closure $setMetadata, ?LoggerInterface $logger = null, ?float $beta = null): mixed
  31. {
  32. if (!$item->isHit() || null === $message = EarlyExpirationMessage::create($this->reverseContainer, $callback, $item, $pool)) {
  33. // The item is stale or the callback cannot be reversed: we must compute the value now
  34. $logger?->info('Computing item "{key}" online: '.($item->isHit() ? 'callback cannot be reversed' : 'item is stale'), ['key' => $item->getKey()]);
  35. return null !== $this->callbackWrapper ? ($this->callbackWrapper)($callback, $item, $save, $pool, $setMetadata, $logger, $beta) : $callback($item, $save);
  36. }
  37. $envelope = $this->bus->dispatch($message);
  38. if ($logger) {
  39. if ($envelope->last(HandledStamp::class)) {
  40. $logger->info('Item "{key}" was computed online', ['key' => $item->getKey()]);
  41. } else {
  42. $logger->info('Item "{key}" sent for recomputation', ['key' => $item->getKey()]);
  43. }
  44. }
  45. // The item's value is not stale, no need to write it to the backend
  46. $save = false;
  47. return $message->getItem()->get() ?? $item->get();
  48. }
  49. }