1 | <?php |
||
7 | class RuntimeCache |
||
8 | { |
||
9 | /** |
||
10 | * Cache. |
||
11 | * |
||
12 | * @var array [ |
||
13 | * 'instance' => Model, |
||
14 | * 'attributes' => [] |
||
15 | * ] |
||
16 | */ |
||
17 | private $cache = []; |
||
18 | |||
19 | /** |
||
20 | * Return true if cache contains this key. |
||
21 | * |
||
22 | * @param mixed $key |
||
23 | * @return bool |
||
24 | */ |
||
25 | 18 | public function has($key) |
|
29 | |||
30 | /** |
||
31 | * Return instance from cache. |
||
32 | * |
||
33 | * @param mixed $key |
||
34 | * @return Model |
||
35 | */ |
||
36 | public function get($key) |
||
37 | { |
||
38 | return $this->has($key) ? $this->cache[$key]['instance'] : null; |
||
39 | } |
||
40 | |||
41 | /** |
||
42 | * Return all cache keys. |
||
43 | * |
||
44 | * @return array |
||
45 | */ |
||
46 | public function keys() |
||
50 | |||
51 | /** |
||
52 | * Put instance to cache. |
||
53 | * |
||
54 | * @param mixed $key |
||
55 | * @param Model $instance |
||
56 | * @param array $attributes |
||
57 | * @return Model |
||
58 | */ |
||
59 | public function put($key, Model $instance, array $attributes = ['*']) |
||
60 | { |
||
61 | if ($attributes != ['*'] && $this->has($key)) { |
||
62 | $instance = Model::merge($this->cache[$key]['instance'], $instance, $attributes); |
||
63 | $attributes = array_merge($this->cache[$key]['attributes'], $attributes); |
||
64 | } |
||
65 | |||
66 | $this->cache[$key] = [ |
||
67 | 'instance' => $instance, |
||
68 | 'attributes' => $attributes |
||
69 | ]; |
||
70 | |||
71 | return $instance; |
||
72 | } |
||
73 | |||
74 | /** |
||
75 | * Return true if cache has already given attributes. |
||
76 | * |
||
77 | * @param mixed $key |
||
78 | * @param array $attributes |
||
79 | * @return bool |
||
80 | */ |
||
81 | 18 | public function containsAttributes($key, array $attributes = ['*']) |
|
85 | |||
86 | /** |
||
87 | * Return the difference between given attributes and attributes which are already cached. |
||
88 | * |
||
89 | * @param mixed $key |
||
90 | * @param array $attributes |
||
91 | * @return array |
||
92 | */ |
||
93 | 18 | public function getNotCachedAttributes($key, array $attributes = ['*']) |
|
94 | { |
||
95 | 18 | if (!$this->has($key)) { |
|
96 | 18 | return $attributes; |
|
97 | } |
||
98 | $cached_attributes = $this->cache[$key]['attributes']; |
||
99 | return $cached_attributes == ['*'] ? [] : array_diff($attributes, $cached_attributes); |
||
100 | } |
||
101 | |||
102 | /** |
||
103 | * Remove an item from the cache by key. |
||
104 | * |
||
105 | * @param mixed $key |
||
106 | * @return $this |
||
107 | */ |
||
108 | 1 | public function forget($key) |
|
113 | } |
||
114 |