AnnotationCache   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 56
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A get() 0 4 2
A set() 0 8 2
A fetch() 0 9 2
1
<?php
2
/**
3
 * This file is part of the silex-annotation-provider package.
4
 * For the full copyright and license information, please view the LICENSE
5
 * file that was distributed with this source code.
6
 *
7
 * @license       MIT License
8
 * @copyright (c) 2018, Dana Desrosiers <[email protected]>
9
 */
10
11
declare(strict_types=1);
12
13
namespace DDesrosiers\SilexAnnotations\Cache;
14
15
use Psr\SimpleCache\CacheInterface;
16
use Psr\SimpleCache\InvalidArgumentException;
17
18
/**
19
 * Class AnnotationCache wraps a PSR-16 cache implementation.
20
 * Uses an array to store data if no cache object is provided.
21
 *
22
 * @author Dana Desrosiers <[email protected]>
23
 */
24
class AnnotationCache
25
{
26
    /** @var CacheInterface */
27
    private $cache;
28
29
    /** @var array */
30
    private $data;
31
32
    /**
33
     * @param CacheInterface|null $cache
34
     */
35
    public function __construct(CacheInterface $cache = null)
36
    {
37
        $this->cache = $cache;
38
    }
39
40
    /**
41
     * @param $key
42
     * @return mixed|null
43
     * @throws InvalidArgumentException
44
     */
45
    public function get($key)
46
    {
47
        return $this->cache ? $this->cache->get($key) : $this->data[$key] ?? null;
48
    }
49
50
    /**
51
     * @param $key
52
     * @param $data
53
     * @throws InvalidArgumentException
54
     */
55
    public function set($key, $data)
56
    {
57
        if ($this->cache) {
58
            $this->cache->set($key, $data);
59
        } else {
60
            $this->data[$key] = $data;
61
        }
62
    }
63
64
    /**
65
     * @param string   $key
66
     * @param \Closure $closure
67
     * @return mixed|null
68
     * @throws InvalidArgumentException
69
     */
70
    public function fetch(string $key, \Closure $closure)
71
    {
72
        $data = $this->get($key);
73
        if ($data === null) {
74
            $this->set($key, $data = $closure());
75
        }
76
77
        return $data;
78
    }
79
}