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