Completed
Pull Request — final (#490)
by Georges
02:21
created

DriverBaseTrait::driverUnwrapEdate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 4
rs 10
1
<?php
2
/**
3
 *
4
 * This file is part of phpFastCache.
5
 *
6
 * @license MIT License (MIT)
7
 *
8
 * For full copyright and license information, please see the docs/CREDITS.txt file.
9
 *
10
 * @author Khoa Bui (khoaofgod)  <[email protected]> http://www.phpfastcache.com
11
 * @author Georges.L (Geolim4)  <[email protected]>
12
 *
13
 */
14
15
namespace phpFastCache\Core\Pool;
16
17
use phpFastCache\Core\Item\ExtendedCacheItemInterface;
18
use phpFastCache\Exceptions\phpFastCacheInvalidArgumentException;
19
use phpFastCache\Exceptions\phpFastCacheLogicException;
20
21
22
/**
23
 * Class DriverBaseTrait
24
 * @package phpFastCache\Cache
25
 */
26
trait DriverBaseTrait
27
{
28
    use ExtendedCacheItemPoolTrait;
29
30
    /**
31
     * @var array default options, this will be merge to Driver's Options
32
     */
33
    protected $config = [];
34
35
    /**
36
     * @var bool
37
     */
38
    protected $fallback = false;
39
40
    /**
41
     * @var mixed Instance of driver service
42
     */
43
    protected $instance;
44
45
    /**
46
     * @var string
47
     */
48
    protected $driverName;
49
50
    /**
51
     * @param $config_name
52
     * @param string $value
53
     */
54
    public function setup($config_name, $value = '')
55
    {
56
        /**
57
         * Config for class
58
         */
59
        if (is_array($config_name)) {
60
            $this->config = array_merge($this->config, $config_name);
61
        } else {
62
            $this->config[ $config_name ] = $value;
63
        }
64
    }
65
66
    /**
67
     * @return array
68
     */
69
    public function getConfig()
70
    {
71
        return $this->config;
72
    }
73
74
75
    /**
76
     * @return mixed
77
     */
78
    public function getConfigOption($optionName)
79
    {
80
        if (isset($this->config[ $optionName ])) {
81
            return $this->config[ $optionName ];
82
        } else {
83
            return null;
84
        }
85
    }
86
87
    /**
88
     * Encode data types such as object/array
89
     * for driver that does not support
90
     * non-scalar value
91
     * @param $data
92
     * @return string
93
     */
94
    protected function encode($data)
95
    {
96
        return serialize($data);
97
    }
98
99
    /**
100
     * Decode data types such as object/array
101
     * for driver that does not support
102
     * non-scalar value
103
     * @param $value
104
     * @return mixed
105
     */
106
    protected function decode($value)
107
    {
108
        return @unserialize($value);
109
    }
110
111
    /**
112
     * Check phpModules or CGI
113
     * @return bool
114
     */
115
    protected function isPHPModule()
116
    {
117
        return (PHP_SAPI === 'apache2handler' || strpos(PHP_SAPI, 'handler') !== false);
118
    }
119
120
121
    /**
122
     * @param $class
123
     * @return bool
124
     */
125
    protected function isExistingDriver($class)
126
    {
127
        return class_exists("\\phpFastCache\\Drivers\\{$class}");
128
    }
129
130
131
    /**
132
     * @param $tag
133
     * @return string
134
     */
135
    protected function _getTagName($tag)
136
    {
137
        return "__tag__" . $tag;
138
    }
139
140
    /**
141
     * @param \phpFastCache\Core\Item\ExtendedCacheItemInterface $item
142
     * @return array
143
     */
144
    public function driverPreWrap(ExtendedCacheItemInterface $item)
145
    {
146
        $wrap = [
147
          self::DRIVER_DATA_WRAPPER_INDEX => $item->get(),
148
          self::DRIVER_TAGS_WRAPPER_INDEX => $item->getTags(),
149
          self::DRIVER_EDATE_WRAPPER_INDEX => $item->getExpirationDate(),
150
        ];
151
152
        if ($this->config[ 'itemDetailedDate' ]) {
153
            $wrap[ self::DRIVER_MDATE_WRAPPER_INDEX ] = new \DateTime();
154
            /**
155
             * If the creation date exists
156
             * reuse it else set a new Date
157
             */
158
            $wrap[ self::DRIVER_CDATE_WRAPPER_INDEX ] = $item->getCreationDate() ?: new \DateTime();
159
        } else {
160
            $wrap[ self::DRIVER_MDATE_WRAPPER_INDEX ] = null;
161
            $wrap[ self::DRIVER_CDATE_WRAPPER_INDEX ] = null;
162
        }
163
164
        return $wrap;
165
    }
166
167
    /**
168
     * @param array $wrapper
169
     * @return mixed
170
     */
171
    public function driverUnwrapData(array $wrapper)
172
    {
173
        return $wrapper[ self::DRIVER_DATA_WRAPPER_INDEX ];
174
    }
175
176
    /**
177
     * @param array $wrapper
178
     * @return mixed
179
     */
180
    public function driverUnwrapTags(array $wrapper)
181
    {
182
        return $wrapper[ self::DRIVER_TAGS_WRAPPER_INDEX ];
183
    }
184
185
186
    /**
187
     * @param array $wrapper
188
     * @return \DateTime
189
     */
190
    public function driverUnwrapEdate(array $wrapper)
191
    {
192
        return $wrapper[ self::DRIVER_EDATE_WRAPPER_INDEX ];
193
    }
194
195
    /**
196
     * @param array $wrapper
197
     * @return \DateTime
198
     */
199
    public function driverUnwrapCdate(array $wrapper)
200
    {
201
        return $wrapper[ self::DRIVER_CDATE_WRAPPER_INDEX ];
202
    }
203
204
205
    /**
206
     * @param array $wrapper
207
     * @return \DateTime
208
     */
209
    public function driverUnwrapMdate(array $wrapper)
210
    {
211
        return $wrapper[ self::DRIVER_MDATE_WRAPPER_INDEX ];
212
    }
213
214
    /**
215
     * @return string
216
     */
217
    public function getDriverName()
218
    {
219
        if(!$this->driverName){
220
            $this->driverName = ucfirst(substr(strrchr((new \ReflectionObject($this))->getNamespaceName(), '\\'), 1));
221
        }
222
        return $this->driverName;
223
    }
224
225
    /**
226
     * @param \phpFastCache\Core\Item\ExtendedCacheItemInterface $item
227
     * @return bool
228
     * @throws phpFastCacheLogicException
229
     */
230
    public function driverWriteTags(ExtendedCacheItemInterface $item)
231
    {
232
        /**
233
         * Do not attempt to write tags
234
         * on tags item, it can leads
235
         * to an infinite recursive calls
236
         */
237
        if (strpos($item->getKey(), self::DRIVER_TAGS_KEY_PREFIX) === 0) {
238
            throw new phpFastCacheLogicException('Trying to set tag(s) to an Tag item index: ' . $item->getKey());
239
        }
240
241
        if(!$item->getTags() && !$item->getRemovedTags())
242
        {
243
            return true;
244
        }
245
246
        /**
247
         * @var $tagsItems ExtendedCacheItemInterface[]
248
         */
249
        $tagsItems = $this->getItems($this->getTagKeys($item->getTags()));
250
251
        foreach ($tagsItems as $tagsItem) {
252
            $data = $tagsItem->get();
253
            $expTimestamp = $item->getExpirationDate()->getTimestamp();
254
255
            /**
256
             * Using the key will
257
             * avoid to use array_unique
258
             * that has slow performances
259
             */
260
261
            $tagsItem->set(array_merge((array)$data, [$item->getKey() => $expTimestamp]));
262
263
            /**
264
             * Set the expiration date
265
             * of the $tagsItem based
266
             * on the older $item
267
             * expiration date
268
             */
269
            if ($expTimestamp > $tagsItem->getExpirationDate()->getTimestamp()) {
270
                $tagsItem->expiresAt($item->getExpirationDate());
271
            }
272
            $this->driverWrite($tagsItem);
273
            $tagsItem->setHit(true);
274
        }
275
276
        /**
277
         * Also update removed tags to
278
         * keep the index up to date
279
         */
280
        $tagsItems = $this->getItems($this->getTagKeys($item->getRemovedTags()));
281
282
        foreach ($tagsItems as $tagsItem) {
283
            $data = (array)$tagsItem->get();
284
285
            unset($data[ $item->getKey() ]);
286
            $tagsItem->set($data);
287
288
            /**
289
             * Recalculate the expiration date
290
             *
291
             * If the $tagsItem does not have
292
             * any cache item references left
293
             * then remove it from tagsItems index
294
             */
295
            if (count($data)) {
296
                $tagsItem->expiresAt(max($data));
297
                $this->driverWrite($tagsItem);
298
                $tagsItem->setHit(true);
299
            } else {
300
                $this->deleteItem($tagsItem->getKey());
301
            }
302
        }
303
304
        return true;
305
    }
306
307
    /**
308
     * @param $key
309
     * @return string
310
     */
311
    public function getTagKey($key)
312
    {
313
        return self::DRIVER_TAGS_KEY_PREFIX . $key;
314
    }
315
316
    /**
317
     * @param $key
318
     * @return array
319
     */
320
    public function getTagKeys(array $keys)
321
    {
322
        foreach ($keys as &$key) {
323
            $key = $this->getTagKey($key);
324
        }
325
326
        return $keys;
327
    }
328
329
    /**
330
     * @param string $optionName
331
     * @param mixed $optionValue
332
     * @return bool
333
     * @throws phpFastCacheInvalidArgumentException
334
     */
335
    public static function isValidOption($optionName, $optionValue)
336
    {
337
        if (!is_string($optionName)) {
338
            throw new phpFastCacheInvalidArgumentException('$optionName must be a string');
339
        }
340
341
        return true;
342
    }
343
344
    /**
345
     * @return array
346
     */
347
    public static function getRequiredOptions()
348
    {
349
        return [];
350
    }
351
352
    /**
353
     * @return array
354
     */
355
    public static function getValidOptions()
356
    {
357
        return [];
358
    }
359
}