CacheTrait.php 2.4 KB

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