summaryrefslogtreecommitdiff
path: root/vendor/symfony/cache-contracts/CacheTrait.php
diff options
context:
space:
mode:
Diffstat (limited to 'vendor/symfony/cache-contracts/CacheTrait.php')
-rw-r--r--vendor/symfony/cache-contracts/CacheTrait.php72
1 files changed, 72 insertions, 0 deletions
diff --git a/vendor/symfony/cache-contracts/CacheTrait.php b/vendor/symfony/cache-contracts/CacheTrait.php
new file mode 100644
index 0000000..c2f6580
--- /dev/null
+++ b/vendor/symfony/cache-contracts/CacheTrait.php
@@ -0,0 +1,72 @@
1<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Contracts\Cache;
13
14use Psr\Cache\CacheItemPoolInterface;
15use Psr\Cache\InvalidArgumentException;
16use Psr\Log\LoggerInterface;
17
18// Help opcache.preload discover always-needed symbols
19class_exists(InvalidArgumentException::class);
20
21/**
22 * An implementation of CacheInterface for PSR-6 CacheItemPoolInterface classes.
23 *
24 * @author Nicolas Grekas <p@tchwork.com>
25 */
26trait CacheTrait
27{
28 public function get(string $key, callable $callback, ?float $beta = null, ?array &$metadata = null): mixed
29 {
30 return $this->doGet($this, $key, $callback, $beta, $metadata);
31 }
32
33 public function delete(string $key): bool
34 {
35 return $this->deleteItem($key);
36 }
37
38 private function doGet(CacheItemPoolInterface $pool, string $key, callable $callback, ?float $beta, ?array &$metadata = null, ?LoggerInterface $logger = null): mixed
39 {
40 if (0 > $beta ??= 1.0) {
41 throw new class(sprintf('Argument "$beta" provided to "%s::get()" must be a positive number, %f given.', static::class, $beta)) extends \InvalidArgumentException implements InvalidArgumentException {};
42 }
43
44 $item = $pool->getItem($key);
45 $recompute = !$item->isHit() || \INF === $beta;
46 $metadata = $item instanceof ItemInterface ? $item->getMetadata() : [];
47
48 if (!$recompute && $metadata) {
49 $expiry = $metadata[ItemInterface::METADATA_EXPIRY] ?? false;
50 $ctime = $metadata[ItemInterface::METADATA_CTIME] ?? false;
51
52 if ($recompute = $ctime && $expiry && $expiry <= ($now = microtime(true)) - $ctime / 1000 * $beta * log(random_int(1, \PHP_INT_MAX) / \PHP_INT_MAX)) {
53 // force applying defaultLifetime to expiry
54 $item->expiresAt(null);
55 $logger?->info('Item "{key}" elected for early recomputation {delta}s before its expiration', [
56 'key' => $key,
57 'delta' => sprintf('%.1f', $expiry - $now),
58 ]);
59 }
60 }
61
62 if ($recompute) {
63 $save = true;
64 $item->set($callback($item, $save));
65 if ($save) {
66 $pool->save($item);
67 }
68 }
69
70 return $item->get();
71 }
72}