b047880661ff9c8d8bda2d96849e43e294b833da
[friendica-addons.git/.git] / advancedcontentfilter / vendor / symfony / cache / Traits / AbstractTrait.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\Cache\Traits;
13
14 use Psr\Log\LoggerAwareTrait;
15 use Symfony\Component\Cache\CacheItem;
16
17 /**
18  * @author Nicolas Grekas <p@tchwork.com>
19  *
20  * @internal
21  */
22 trait AbstractTrait
23 {
24     use LoggerAwareTrait;
25
26     private $namespace;
27     private $namespaceVersion = '';
28     private $versioningIsEnabled = false;
29     private $deferred = [];
30     private $ids = [];
31
32     /**
33      * @var int|null The maximum length to enforce for identifiers or null when no limit applies
34      */
35     protected $maxIdLength;
36
37     /**
38      * Fetches several cache items.
39      *
40      * @param array $ids The cache identifiers to fetch
41      *
42      * @return array|\Traversable The corresponding values found in the cache
43      */
44     abstract protected function doFetch(array $ids);
45
46     /**
47      * Confirms if the cache contains specified cache item.
48      *
49      * @param string $id The identifier for which to check existence
50      *
51      * @return bool True if item exists in the cache, false otherwise
52      */
53     abstract protected function doHave($id);
54
55     /**
56      * Deletes all items in the pool.
57      *
58      * @param string $namespace The prefix used for all identifiers managed by this pool
59      *
60      * @return bool True if the pool was successfully cleared, false otherwise
61      */
62     abstract protected function doClear($namespace);
63
64     /**
65      * Removes multiple items from the pool.
66      *
67      * @param array $ids An array of identifiers that should be removed from the pool
68      *
69      * @return bool True if the items were successfully removed, false otherwise
70      */
71     abstract protected function doDelete(array $ids);
72
73     /**
74      * Persists several cache items immediately.
75      *
76      * @param array $values   The values to cache, indexed by their cache identifier
77      * @param int   $lifetime The lifetime of the cached values, 0 for persisting until manual cleaning
78      *
79      * @return array|bool The identifiers that failed to be cached or a boolean stating if caching succeeded or not
80      */
81     abstract protected function doSave(array $values, int $lifetime);
82
83     /**
84      * {@inheritdoc}
85      *
86      * @return bool
87      */
88     public function hasItem($key)
89     {
90         $id = $this->getId($key);
91
92         if (isset($this->deferred[$key])) {
93             $this->commit();
94         }
95
96         try {
97             return $this->doHave($id);
98         } catch (\Exception $e) {
99             CacheItem::log($this->logger, 'Failed to check if key "{key}" is cached: '.$e->getMessage(), ['key' => $key, 'exception' => $e]);
100
101             return false;
102         }
103     }
104
105     /**
106      * {@inheritdoc}
107      *
108      * @param string $prefix
109      *
110      * @return bool
111      */
112     public function clear(/* string $prefix = '' */)
113     {
114         $this->deferred = [];
115         if ($cleared = $this->versioningIsEnabled) {
116             if ('' === $namespaceVersionToClear = $this->namespaceVersion) {
117                 foreach ($this->doFetch([static::NS_SEPARATOR.$this->namespace]) as $v) {
118                     $namespaceVersionToClear = $v;
119                 }
120             }
121             $namespaceToClear = $this->namespace.$namespaceVersionToClear;
122             $namespaceVersion = self::formatNamespaceVersion(mt_rand());
123             try {
124                 $e = $this->doSave([static::NS_SEPARATOR.$this->namespace => $namespaceVersion], 0);
125             } catch (\Exception $e) {
126             }
127             if (true !== $e && [] !== $e) {
128                 $cleared = false;
129                 $message = 'Failed to save the new namespace'.($e instanceof \Exception ? ': '.$e->getMessage() : '.');
130                 CacheItem::log($this->logger, $message, ['exception' => $e instanceof \Exception ? $e : null]);
131             } else {
132                 $this->namespaceVersion = $namespaceVersion;
133                 $this->ids = [];
134             }
135         } else {
136             $prefix = 0 < \func_num_args() ? (string) func_get_arg(0) : '';
137             $namespaceToClear = $this->namespace.$prefix;
138         }
139
140         try {
141             return $this->doClear($namespaceToClear) || $cleared;
142         } catch (\Exception $e) {
143             CacheItem::log($this->logger, 'Failed to clear the cache: '.$e->getMessage(), ['exception' => $e]);
144
145             return false;
146         }
147     }
148
149     /**
150      * {@inheritdoc}
151      *
152      * @return bool
153      */
154     public function deleteItem($key)
155     {
156         return $this->deleteItems([$key]);
157     }
158
159     /**
160      * {@inheritdoc}
161      *
162      * @return bool
163      */
164     public function deleteItems(array $keys)
165     {
166         $ids = [];
167
168         foreach ($keys as $key) {
169             $ids[$key] = $this->getId($key);
170             unset($this->deferred[$key]);
171         }
172
173         try {
174             if ($this->doDelete($ids)) {
175                 return true;
176             }
177         } catch (\Exception $e) {
178         }
179
180         $ok = true;
181
182         // When bulk-delete failed, retry each item individually
183         foreach ($ids as $key => $id) {
184             try {
185                 $e = null;
186                 if ($this->doDelete([$id])) {
187                     continue;
188                 }
189             } catch (\Exception $e) {
190             }
191             $message = 'Failed to delete key "{key}"'.($e instanceof \Exception ? ': '.$e->getMessage() : '.');
192             CacheItem::log($this->logger, $message, ['key' => $key, 'exception' => $e]);
193             $ok = false;
194         }
195
196         return $ok;
197     }
198
199     /**
200      * Enables/disables versioning of items.
201      *
202      * When versioning is enabled, clearing the cache is atomic and doesn't require listing existing keys to proceed,
203      * but old keys may need garbage collection and extra round-trips to the back-end are required.
204      *
205      * Calling this method also clears the memoized namespace version and thus forces a resynchonization of it.
206      *
207      * @param bool $enable
208      *
209      * @return bool the previous state of versioning
210      */
211     public function enableVersioning($enable = true)
212     {
213         $wasEnabled = $this->versioningIsEnabled;
214         $this->versioningIsEnabled = (bool) $enable;
215         $this->namespaceVersion = '';
216         $this->ids = [];
217
218         return $wasEnabled;
219     }
220
221     /**
222      * {@inheritdoc}
223      */
224     public function reset()
225     {
226         if ($this->deferred) {
227             $this->commit();
228         }
229         $this->namespaceVersion = '';
230         $this->ids = [];
231     }
232
233     /**
234      * Like the native unserialize() function but throws an exception if anything goes wrong.
235      *
236      * @param string $value
237      *
238      * @return mixed
239      *
240      * @throws \Exception
241      *
242      * @deprecated since Symfony 4.2, use DefaultMarshaller instead.
243      */
244     protected static function unserialize($value)
245     {
246         @trigger_error(sprintf('The "%s::unserialize()" method is deprecated since Symfony 4.2, use DefaultMarshaller instead.', __CLASS__), \E_USER_DEPRECATED);
247
248         if ('b:0;' === $value) {
249             return false;
250         }
251         $unserializeCallbackHandler = ini_set('unserialize_callback_func', __CLASS__.'::handleUnserializeCallback');
252         try {
253             if (false !== $value = unserialize($value)) {
254                 return $value;
255             }
256             throw new \DomainException('Failed to unserialize cached value.');
257         } catch (\Error $e) {
258             throw new \ErrorException($e->getMessage(), $e->getCode(), \E_ERROR, $e->getFile(), $e->getLine());
259         } finally {
260             ini_set('unserialize_callback_func', $unserializeCallbackHandler);
261         }
262     }
263
264     private function getId($key): string
265     {
266         if ($this->versioningIsEnabled && '' === $this->namespaceVersion) {
267             $this->ids = [];
268             $this->namespaceVersion = '1'.static::NS_SEPARATOR;
269             try {
270                 foreach ($this->doFetch([static::NS_SEPARATOR.$this->namespace]) as $v) {
271                     $this->namespaceVersion = $v;
272                 }
273                 $e = true;
274                 if ('1'.static::NS_SEPARATOR === $this->namespaceVersion) {
275                     $this->namespaceVersion = self::formatNamespaceVersion(time());
276                     $e = $this->doSave([static::NS_SEPARATOR.$this->namespace => $this->namespaceVersion], 0);
277                 }
278             } catch (\Exception $e) {
279             }
280             if (true !== $e && [] !== $e) {
281                 $message = 'Failed to save the new namespace'.($e instanceof \Exception ? ': '.$e->getMessage() : '.');
282                 CacheItem::log($this->logger, $message, ['exception' => $e instanceof \Exception ? $e : null]);
283             }
284         }
285
286         if (\is_string($key) && isset($this->ids[$key])) {
287             return $this->namespace.$this->namespaceVersion.$this->ids[$key];
288         }
289         CacheItem::validateKey($key);
290         $this->ids[$key] = $key;
291
292         if (\count($this->ids) > 1000) {
293             $this->ids = \array_slice($this->ids, 500, null, true); // stop memory leak if there are many keys
294         }
295
296         if (null === $this->maxIdLength) {
297             return $this->namespace.$this->namespaceVersion.$key;
298         }
299         if (\strlen($id = $this->namespace.$this->namespaceVersion.$key) > $this->maxIdLength) {
300             // Use MD5 to favor speed over security, which is not an issue here
301             $this->ids[$key] = $id = substr_replace(base64_encode(hash('md5', $key, true)), static::NS_SEPARATOR, -(\strlen($this->namespaceVersion) + 2));
302             $id = $this->namespace.$this->namespaceVersion.$id;
303         }
304
305         return $id;
306     }
307
308     /**
309      * @internal
310      */
311     public static function handleUnserializeCallback($class)
312     {
313         throw new \DomainException('Class not found: '.$class);
314     }
315
316     private static function formatNamespaceVersion(int $value): string
317     {
318         return strtr(substr_replace(base64_encode(pack('V', $value)), static::NS_SEPARATOR, 5), '/', '_');
319     }
320 }