CacheTrait.php 2.5 KB

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