Passed
Pull Request — master (#838)
by Georges
04:11 queued 02:01
created

CacheContract   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 38
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A get() 0 17 3
A __invoke() 0 3 1
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