CacheTrait.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. /**
  14. * An implementation of CacheInterface for PSR-6 CacheItemPoolInterface classes.
  15. *
  16. * @author Nicolas Grekas <p@tchwork.com>
  17. */
  18. trait CacheTrait
  19. {
  20. /**
  21. * {@inheritdoc}
  22. */
  23. public function get(string $key, callable $callback, float $beta = null, array &$metadata = null)
  24. {
  25. return $this->doGet($this, $key, $callback, $beta, $metadata);
  26. }
  27. /**
  28. * {@inheritdoc}
  29. */
  30. public function delete(string $key): bool
  31. {
  32. return $this->deleteItem($key);
  33. }
  34. private function doGet(CacheItemPoolInterface $pool, string $key, callable $callback, ?float $beta, array &$metadata = null)
  35. {
  36. if (0 > $beta = $beta ?? 1.0) {
  37. 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 {
  38. };
  39. }
  40. $item = $pool->getItem($key);
  41. $recompute = !$item->isHit() || INF === $beta;
  42. $metadata = $item instanceof ItemInterface ? $item->getMetadata() : array();
  43. if (!$recompute && $metadata) {
  44. $expiry = $metadata[ItemInterface::METADATA_EXPIRY] ?? false;
  45. $ctime = $metadata[ItemInterface::METADATA_CTIME] ?? false;
  46. if ($recompute = $ctime && $expiry && $expiry <= microtime(true) - $ctime / 1000 * $beta * log(random_int(1, PHP_INT_MAX) / PHP_INT_MAX)) {
  47. // force applying defaultLifetime to expiry
  48. $item->expiresAt(null);
  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. }