Issues (21)

src/Cache.php (1 issue)

1
<?php
2
3
/**
4
 * This file is part of the Phalcon Framework.
5
 *
6
 * (c) Phalcon Team <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE.txt
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Phalcon;
13
14
use DateInterval;
15
use Phalcon\Cache\Adapter\AdapterInterface;
16
use Phalcon\Cache\Exception\InvalidArgumentException;
17
use Psr\SimpleCache\CacheInterface;
18
use Traversable;
19
20
use function is_array;
21
use function preg_match;
22
23
/**
24
 * This component offers caching capabilities for your application.
25
 * Phalcon\Cache implements PSR-16.
26
 *
27
 * @property AdapterInterface $adapter
28
 */
29
class Cache implements CacheInterface
30
{
31
    /**
32
     * The adapter
33
     *
34
     * @var AdapterInterface
35
     */
36
    protected $adapter;
37
38
    /**
39
     * Constructor.
40
     *
41
     * @param AdapterInterface $adapter The cache adapter
42
     */
43 32
    public function __construct(AdapterInterface $adapter)
44
    {
45 32
        $this->adapter = $adapter;
46 32
    }
47
48
    /**
49
     * Returns the current cache adapter
50
     *
51
     * @return AdapterInterface
52
     */
53 2
    public function getAdapter(): AdapterInterface
54
    {
55 2
        return $this->adapter;
56
    }
57
58
    /**
59
     * Wipes clean the entire cache's keys.
60
     *
61
     * @return bool True on success and false on failure.
62
     */
63 2
    public function clear(): bool
64
    {
65 2
        return $this->adapter->clear();
66
    }
67
68
    /**
69
     * Delete an item from the cache by its unique key.
70
     *
71
     * @param string $key The unique cache key of the item to delete.
72
     *
73
     * @return bool True if the item was successfully removed. False if there
74
     * was an error.
75
     *
76
     * @throws InvalidArgumentException MUST be thrown if the $key string is
77
     * not a legal value.
78
     */
79 6
    public function delete($key): bool
80
    {
81 6
        $this->checkKey($key);
82
83 4
        return $this->adapter->delete($key);
84
    }
85
86
    /**
87
     * Deletes multiple cache items in a single operation.
88
     *
89
     * @param iterable $keys A list of string-based keys to be deleted.
90
     *
91
     * @return bool True if the items were successfully removed. False if
92
     * there was an error.
93
     *
94
     * @throws InvalidArgumentException MUST be thrown if $keys is neither an
95
     * array nor a Traversable, or if any of the $keys are not a legal value.
96
     */
97 4
    public function deleteMultiple($keys): bool
98
    {
99 4
        $this->checkKeys($keys);
100
101 2
        $result = true;
102 2
        foreach ($keys as $key) {
103 2
            if (!$this->adapter->delete($key)) {
104 2
                $result = false;
105
            }
106
        }
107
108 2
        return $result;
109
    }
110
111
    /**
112
     * Fetches a value from the cache.
113
     *
114
     * @param string $key          The unique key of this item in the cache.
115
     * @param mixed  $defaultValue Default value to return if the key does
116
     *                             not exist.
117
     *
118
     * @return mixed The value of the item from the cache, or $default in case
119
     * of cache miss.
120
     *
121
     * @throws InvalidArgumentException MUST be thrown if the $key string is
122
     * not a legal value.
123
     */
124 8
    public function get($key, $defaultValue = null)
125
    {
126 8
        $this->checkKey($key);
127
128 6
        return $this->adapter->get($key, $defaultValue);
129
    }
130
131
    /**
132
     * Obtains multiple cache items by their unique keys.
133
     *
134
     * @param iterable $keys         A list of keys that can obtained in a
135
     *                               single operation.
136
     * @param mixed    $defaultValue Default value to return for keys that do
137
     *                               not exist.
138
     *
139
     * @return iterable A list of key => value pairs. Cache keys that do not
140
     * exist or are stale will have $default as value.
141
     *
142
     * @throws InvalidArgumentException MUST be thrown if $keys is neither an
143
     * array nor a Traversable, or if any of the $keys are not a legal value.
144
     */
145 6
    public function getMultiple($keys, $defaultValue = null)
146
    {
147 6
        $this->checkKeys($keys);
148
149 4
        $results = [];
150 4
        foreach ($keys as $element) {
151 4
            $results[$element] = $this->get($element, $defaultValue);
152
        }
153
154 4
        return $results;
155
    }
156
157
    /**
158
     * Determines whether an item is present in the cache.
159
     *
160
     * @param string $key The cache item key.
161
     *
162
     * @return bool
163
     *
164
     * @throws InvalidArgumentException MUST be thrown if the $key string is
165
     * not a legal value.
166
     */
167 16
    public function has($key): bool
168
    {
169 16
        $this->checkKey($key);
170
171 14
        return $this->adapter->has($key);
172
    }
173
174
    /**
175
     * Persists data in the cache, uniquely referenced by a key with an
176
     * optional expiration TTL time.
177
     *
178
     * @param string                $key    The key of the item to store.
179
     * @param mixed                 $value  The value of the item to store.
180
     *                                      Must be serializable.
181
     * @param null|int|DateInterval $ttl    Optional. The TTL value of this
182
     *                                      item. If no value is sent and the
183
     *                                      driver supports TTL then the
184
     *                                      library may set a default value
185
     *                                      for it or let the driver take care
186
     *                                      of that.
187
     *
188
     * @return bool True on success and false on failure.
189
     *
190
     * @throws InvalidArgumentException MUST be thrown if the $key string is
191
     * not a legal value.
192
     */
193 18
    public function set($key, $value, $ttl = null): bool
194
    {
195 18
        $this->checkKey($key);
196
197 14
        return $this->adapter->set($key, $value, $ttl);
198
    }
199
200
    /**
201
     * Persists a set of key => value pairs in the cache, with an optional TTL.
202
     *
203
     * @param iterable              $values  A list of key => value pairs for
204
     *                                       a multiple-set operation.
205
     * @param null|int|DateInterval $ttl     Optional. The TTL value of this
206
     *                                       item. If no value is sent and the
207
     *                                       driver supports TTL then the
208
     *                                       library may set a default value
209
     *                                       for it or let the driver take
210
     *                                       care of that.
211
     *
212
     * @return bool True on success and false on failure.
213
     *
214
     * @throws InvalidArgumentException MUST be thrown if $values is neither
215
     * an array nor a Traversable, or if any of the $values are not a legal
216
     * value.
217
     */
218 6
    public function setMultiple($values, $ttl = null): bool
219
    {
220 6
        $this->checkKeys($values);
221
222 6
        $result = true;
223 6
        foreach ($values as $key => $value) {
224 6
            if (!$this->set($key, $value, $ttl)) {
225
                $result = false;
226
            }
227
        }
228
229 4
        return $result;
230
    }
231
232
    /**
233
     * Checks the key. If it contains invalid characters an exception is thrown
234
     *
235
     * @param mixed $key
236
     *
237
     * @throws InvalidArgumentException
238
     */
239 22
    protected function checkKey($key): void
240
    {
241 22
        $key = (string) $key;
242
243 22
        if (preg_match("/[^A-Za-z0-9-_.]/", $key)) {
244 8
            throw new InvalidArgumentException(
245 8
                "The key contains invalid characters"
246
            );
247
        }
248 14
    }
249
250
    /**
251
     * Checks the key. If it contains invalid characters an exception is thrown
252
     *
253
     * @param array|Traversable $keys
254
     *
255
     * @throws InvalidArgumentException
256
     */
257 12
    protected function checkKeys($keys): void
258
    {
259 12
        if (!(is_array($keys) || $keys instanceof Traversable)) {
0 ignored issues
show
$keys is always a sub-type of Traversable.
Loading history...
260 6
            throw new InvalidArgumentException(
261 6
                "The keys need to be an array or instance of Traversable"
262
            );
263
        }
264 8
    }
265
}
266