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

Open in your IDE?
  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\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 <p@tchwork.com>
  20.  */
  21. trait CacheTrait
  22. {
  23.     /**
  24.      * {@inheritdoc}
  25.      *
  26.      * @return mixed
  27.      */
  28.     public function get(string $key, callable $callbackfloat $beta null, array &$metadata null)
  29.     {
  30.         return $this->doGet($this$key$callback$beta$metadata);
  31.     }
  32.     /**
  33.      * {@inheritdoc}
  34.      */
  35.     public function delete(string $key): bool
  36.     {
  37.         return $this->deleteItem($key);
  38.     }
  39.     private function doGet(CacheItemPoolInterface $poolstring $key, callable $callback, ?float $beta, array &$metadata nullLoggerInterface $logger null)
  40.     {
  41.         if ($beta $beta ?? 1.0) {
  42.             throw new class(sprintf('Argument "$beta" provided to "%s::get()" must be a positive number, %f given.', static::class, $beta)) extends \InvalidArgumentException implements InvalidArgumentException { };
  43.         }
  44.         $item $pool->getItem($key);
  45.         $recompute = !$item->isHit() || \INF === $beta;
  46.         $metadata $item instanceof ItemInterface $item->getMetadata() : [];
  47.         if (!$recompute && $metadata) {
  48.             $expiry $metadata[ItemInterface::METADATA_EXPIRY] ?? false;
  49.             $ctime $metadata[ItemInterface::METADATA_CTIME] ?? false;
  50.             if ($recompute $ctime && $expiry && $expiry <= ($now microtime(true)) - $ctime 1000 $beta log(random_int(1\PHP_INT_MAX) / \PHP_INT_MAX)) {
  51.                 // force applying defaultLifetime to expiry
  52.                 $item->expiresAt(null);
  53.                 $logger && $logger->info('Item "{key}" elected for early recomputation {delta}s before its expiration', [
  54.                     'key' => $key,
  55.                     'delta' => sprintf('%.1f'$expiry $now),
  56.                 ]);
  57.             }
  58.         }
  59.         if ($recompute) {
  60.             $save true;
  61.             $item->set($callback($item$save));
  62.             if ($save) {
  63.                 $pool->save($item);
  64.             }
  65.         }
  66.         return $item->get();
  67.     }
  68. }