CacheTrait.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. 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. /**
  32. * @param-immediately-invoked-callable $callback
  33. */
  34. private function doGet(CacheItemPoolInterface $pool, string $key, callable $callback, ?float $beta, ?array &$metadata = null, ?LoggerInterface $logger = null): mixed
  35. {
  36. if (0 > $beta ??= 1.0) {
  37. throw new class(\sprintf('Argument "$beta" provided to "%s::get()" must be a positive number, %f given.', static::class, $beta)) extends \InvalidArgumentException implements InvalidArgumentException {};
  38. }
  39. $item = $pool->getItem($key);
  40. $recompute = !$item->isHit() || \INF === $beta;
  41. $metadata = $item instanceof ItemInterface ? $item->getMetadata() : [];
  42. if (!$recompute && $metadata) {
  43. $expiry = $metadata[ItemInterface::METADATA_EXPIRY] ?? false;
  44. $ctime = $metadata[ItemInterface::METADATA_CTIME] ?? false;
  45. if ($recompute = $ctime && $expiry && $expiry <= ($now = microtime(true)) - $ctime / 1000 * $beta * log(random_int(1, \PHP_INT_MAX) / \PHP_INT_MAX)) {
  46. // force applying defaultLifetime to expiry
  47. $item->expiresAt(null);
  48. $logger?->info('Item "{key}" elected for early recomputation {delta}s before its expiration', [
  49. 'key' => $key,
  50. 'delta' => \sprintf('%.1f', $expiry - $now),
  51. ]);
  52. }
  53. }
  54. if ($recompute) {
  55. $save = true;
  56. $item->set($callback($item, $save));
  57. if ($save) {
  58. $pool->save($item);
  59. }
  60. }
  61. return $item->get();
  62. }
  63. }