Passed
Pull Request — master (#79)
by David
02:19
created

SelfValidatingCache   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
dl 0
loc 42
c 0
b 0
f 0
eloc 10
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A set() 0 6 2
A __construct() 0 3 1
A get() 0 7 2
1
<?php
2
3
4
namespace TheCodingMachine\GraphQL\Controllers\Cache;
5
6
7
use Psr\SimpleCache\CacheInterface;
8
9
class SelfValidatingCache implements SelfValidatingCacheInterface
10
{
11
12
    /**
13
     * @var CacheInterface
14
     */
15
    private $cache;
16
17
    public function __construct(CacheInterface $cache)
18
    {
19
        $this->cache = $cache;
20
    }
21
22
    /**
23
     * Fetches a value from the cache.
24
     *
25
     * @param string $key The unique key of this item in the cache.
26
     *
27
     * @return mixed The value of the item from the cache, or null in case of cache miss.
28
     */
29
    public function get(string $key)
30
    {
31
        $item = $this->cache->get($key);
32
        if (!$item instanceof CacheValidatorInterface) {
33
            throw InvalidCacheItemException::create($key);
34
        }
35
        return $item;
36
    }
37
38
    /**
39
     * Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time.
40
     *
41
     * @param string $key The key of the item to store.
42
     * @param mixed $value The value of the item to store, must be serializable.
43
     *
44
     */
45
    public function set(string $key, $value)
46
    {
47
        if (!$value instanceof CacheValidatorInterface) {
48
            throw InvalidCacheItemException::create($key);
49
        }
50
        $this->cache->set($key, $value);
51
    }
52
}
53