vendor/symfony/cache-contracts/CacheTrait.php line 64

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <[email protected]>
  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\Contracts\Cache;
  11. use Psr\Cache\CacheItemPoolInterface;
  12. use Psr\Cache\InvalidArgumentException;
  13. use Psr\Log\LoggerInterface;
  14. // Help opcache.preload discover always-needed symbols
  15. class_exists(InvalidArgumentException::class);
  16. /**
  17.  * An implementation of CacheInterface for PSR-6 CacheItemPoolInterface classes.
  18.  *
  19.  * @author Nicolas Grekas <[email protected]>
  20.  */
  21. trait CacheTrait
  22. {
  23.     public function get(string $key, callable $callback, ?float $beta null, ?array &$metadata null): mixed
  24.     {
  25.         return $this->doGet($this$key$callback$beta$metadata);
  26.     }
  27.     public function delete(string $key): bool
  28.     {
  29.         return $this->deleteItem($key);
  30.     }
  31.     private function doGet(CacheItemPoolInterface $poolstring $key, callable $callback, ?float $beta, ?array &$metadata null, ?LoggerInterface $logger null): mixed
  32.     {
  33.         if ($beta ??= 1.0) {
  34.             throw new class(\sprintf('Argument "$beta" provided to "%s::get()" must be a positive number, %f given.', static::class, $beta)) extends \InvalidArgumentException implements InvalidArgumentException {};
  35.         }
  36.         $item $pool->getItem($key);
  37.         $recompute = !$item->isHit() || \INF === $beta;
  38.         $metadata $item instanceof ItemInterface $item->getMetadata() : [];
  39.         if (!$recompute && $metadata) {
  40.             $expiry $metadata[ItemInterface::METADATA_EXPIRY] ?? false;
  41.             $ctime $metadata[ItemInterface::METADATA_CTIME] ?? false;
  42.             if ($recompute $ctime && $expiry && $expiry <= ($now microtime(true)) - $ctime 1000 $beta log(random_int(1\PHP_INT_MAX) / \PHP_INT_MAX)) {
  43.                 // force applying defaultLifetime to expiry
  44.                 $item->expiresAt(null);
  45.                 $logger?->info('Item "{key}" elected for early recomputation {delta}s before its expiration', [
  46.                     'key' => $key,
  47.                     'delta' => \sprintf('%.1f'$expiry $now),
  48.                 ]);
  49.             }
  50.         }
  51.         if ($recompute) {
  52.             $save true;
  53.             $item->set($callback($item$save));
  54.             if ($save) {
  55.                 $pool->save($item);
  56.             }
  57.         }
  58.         return $item->get();
  59.     }
  60. }