Completed
Push — master ( 3d22df...95226d )
by Georges
22s queued 12s
created

CacheContract::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 1
b 0
f 0
1
<?php
2
3
/**
4
 *
5
 * This file is part of Phpfastcache.
6
 *
7
 * @license MIT License (MIT)
8
 *
9
 * For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
10
 *
11
 * @author Georges.L (Geolim4)  <[email protected]>
12
 * @author Contributors  https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
13
 */
14
declare(strict_types=1);
15
16
namespace Phpfastcache;
17
18
use DateInterval;
19
use Psr\Cache\CacheItemPoolInterface;
20
use Psr\Cache\InvalidArgumentException;
21
22
class CacheContract
23
{
24
    protected CacheItemPoolInterface $cacheInstance;
25
26
    public function __construct(CacheItemPoolInterface $cacheInstance)
27
    {
28
        $this->cacheInstance = $cacheInstance;
29
    }
30
31
    /**
32
     * @param  string                    $cacheKey
33
     * @param  callable                  $callback
34
     * @param  DateInterval|integer|null $expiresAfter
35
     * @return mixed
36
     * @throws InvalidArgumentException
37
     */
38
    public function get(string $cacheKey, callable $callback, DateInterval|int $expiresAfter = null): mixed
39
    {
40
        $cacheItem = $this->cacheInstance->getItem($cacheKey);
41
42
        if (! $cacheItem->isHit()) {
43
            /*
44
            * Parameter $cacheItem will be available as of 8.0.6
45
            */
46
            $cacheItem->set($callback($cacheItem));
47
            if ($expiresAfter) {
48
                $cacheItem->expiresAfter($expiresAfter);
49
            }
50
51
            $this->cacheInstance->save($cacheItem);
52
        }
53
54
        return $cacheItem->get();
55
    }
56
57
    public function __invoke(...$args): mixed
58
    {
59
        return $this->get(...$args);
60
    }
61
}
62