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
|
|
|
} |