Completed
Push — v5 ( 2766dd...bcb79b )
by Georges
02:36
created

DriverBaseTrait::isValidOption()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 4
c 1
b 0
f 1
nc 2
nop 2
dl 0
loc 8
rs 9.4285
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
namespace phpFastCache\Cache;
15
16
use phpFastCache\Core\ExtendedCacheItemPoolTrait;
17
use phpFastCache\Exceptions\phpFastCacheDriverException;
18
19
/**
20
 * Class DriverBaseTrait
21
 * @package phpFastCache\Cache
22
 */
23
trait DriverBaseTrait
24
{
25
    use ExtendedCacheItemPoolTrait;
26
27
    /**
28
     * @var array
29
     */
30
    public $extension_dir = '_extensions';
31
32
    /**
33
     * @var array default options, this will be merge to Driver's Options
34
     */
35
    public $config = [];
36
37
    /**
38
     * @var bool
39
     */
40
    public $fallback = false;
41
42
    /**
43
     * @var mixed Instance of driver service
44
     */
45
    public $instance;
46
47
    /**
48
     * @param $keyword
49
     * @return string
50
     */
51
    protected function encodeFilename($keyword)
52
    {
53
        return md5($keyword);
54
    }
55
56
    /**
57
     * @param $config_name
58
     * @param string $value
59
     */
60
    public function setup($config_name, $value = '')
61
    {
62
        /**
63
         * Config for class
64
         */
65
        if (is_array($config_name)) {
66
            $this->config = array_merge($this->config, $config_name);
67
        } else {
68
            $this->config[ $config_name ] = $value;
69
        }
70
    }
71
72
73
    /**
74
     * @param $file
75
     * @return string
76
     * @throws \Exception
77
     */
78
    protected function readfile($file)
79
    {
80
        if (function_exists('file_get_contents')) {
81
            return file_get_contents($file);
0 ignored issues
show
Security File Exposure introduced by
$file can contain request data and is used in file inclusion context(s) leading to a potential security vulnerability.

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
82
        } else {
83
            $string = '';
84
85
            $file_handle = @fopen($file, 'r');
86
            if (!$file_handle) {
87
                throw new phpFastCacheDriverException("Can't Read File", 96);
88
89
            }
90
            while (!feof($file_handle)) {
91
                $line = fgets($file_handle);
92
                $string .= $line;
93
            }
94
            fclose($file_handle);
95
96
            return $string;
97
        }
98
    }
99
100
    /**
101
     * Encode data types such as object/array
102
     * for driver that does not support
103
     * non-scalar value
104
     * @param $data
105
     * @return string
106
     */
107
    protected function encode($data)
108
    {
109
        return serialize($data);
110
    }
111
112
    /**
113
     * Decode data types such as object/array
114
     * for driver that does not support
115
     * non-scalar value
116
     * @param $value
117
     * @return mixed
118
     */
119
    protected function decode($value)
120
    {
121
        $x = @unserialize($value);
0 ignored issues
show
Security Object Injection introduced by
$value can contain request data and is used in unserialized context(s) leading to a potential security vulnerability.

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
122
        if ($x == false) {
123
            return $value;
124
        } else {
125
            return $x;
126
        }
127
    }
128
129
    /**
130
     * Check phpModules or CGI
131
     * @return bool
132
     */
133
    protected function isPHPModule()
134
    {
135
        if (PHP_SAPI === 'apache2handler') {
136
            return true;
137
        } else {
138
            if (strpos(PHP_SAPI, 'handler') !== false) {
139
                return true;
140
            }
141
        }
142
143
        return false;
144
    }
145
146
147
    /**
148
     * @param $class
149
     * @return bool
150
     */
151
    protected function isExistingDriver($class)
152
    {
153
        return class_exists("\\phpFastCache\\Drivers\\{$class}");
154
    }
155
156
157
    /**
158
     * @param $tag
159
     * @return string
160
     */
161
    protected function _getTagName($tag)
162
    {
163
        return "__tag__" . $tag;
164
    }
165
166
    /**
167
     * @param \phpFastCache\Cache\ExtendedCacheItemInterface $item
168
     * @return array
169
     */
170
    public function driverPreWrap(ExtendedCacheItemInterface $item)
171
    {
172
        return [
173
          self::DRIVER_DATA_WRAPPER_INDEX => $item->get(),
174
          self::DRIVER_TIME_WRAPPER_INDEX => $item->getExpirationDate(),
175
          self::DRIVER_TAGS_WRAPPER_INDEX => $item->getTags(),
176
        ];
177
    }
178
179
    /**
180
     * @param array $wrapper
181
     * @return mixed
182
     */
183
    public function driverUnwrapData(array $wrapper)
184
    {
185
        return $wrapper[ self::DRIVER_DATA_WRAPPER_INDEX ];
186
    }
187
188
    /**
189
     * @param array $wrapper
190
     * @return mixed
191
     */
192
    public function driverUnwrapTags(array $wrapper)
193
    {
194
        return $wrapper[ self::DRIVER_TAGS_WRAPPER_INDEX ];
195
    }
196
197
198
    /**
199
     * @param array $wrapper
200
     * @return \DateTime
201
     */
202
    public function driverUnwrapTime(array $wrapper)
203
    {
204
        return $wrapper[ self::DRIVER_TIME_WRAPPER_INDEX ];
205
    }
206
207
    /**
208
     * @return string
209
     */
210
    public function getDriverName()
211
    {
212
        static $driverName;
213
214
        return ($driverName ?: $driverName = ucfirst(substr(strrchr((new \ReflectionObject($this))->getNamespaceName(), '\\'), 1)));
215
    }
216
217
    /**
218
     * @param \phpFastCache\Cache\ExtendedCacheItemInterface $item
219
     * @return bool
220
     */
221
    public function driverWriteTags(ExtendedCacheItemInterface $item)
222
    {
223
        $tagsItems = $this->getItems($this->getTagKeys($item->getTags()));
1 ignored issue
show
Bug introduced by
The method getItems() does not exist on phpFastCache\Cache\DriverBaseTrait. Did you maybe mean getItemsByTag()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
224
225
        foreach ($tagsItems as $tagsItem) {
226
            $data = $tagsItem->get();
227
            $expTimestamp = $item->getExpirationDate()->getTimestamp();
228
229
            /**
230
             * Using the key will
231
             * avoid to use array_unique
232
             * that has slow performances
233
             */
234
235
            $tagsItem->set(array_merge((array) $data, [$item->getKey() => $expTimestamp]));
236
237
            /**
238
             * Set the expiration date
239
             * of the $tagsItem based
240
             * on the older $item
241
             * expiration date
242
             */
243
            if ($expTimestamp > $tagsItem->getExpirationDate()->getTimestamp()) {
244
                $tagsItem->expiresAt($item->getExpirationDate());
245
            }
246
            $this->driverWrite($tagsItem);
1 ignored issue
show
Bug introduced by
The method driverWrite() does not exist on phpFastCache\Cache\DriverBaseTrait. Did you maybe mean driverWriteTags()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
247
        }
248
249
        /**
250
         * Also update removed tags to
251
         * keep the index up to date
252
         */
253
        $tagsItems = $this->getItems($this->getTagKeys($item->getRemovedTags()));
1 ignored issue
show
Bug introduced by
The method getItems() does not exist on phpFastCache\Cache\DriverBaseTrait. Did you maybe mean getItemsByTag()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
254
255
        foreach ($tagsItems as $tagsItem) {
256
            $data = (array) $tagsItem->get();
257
258
            unset($data[ $item->getKey() ]);
259
            $tagsItem->set($data);
260
261
            /**
262
             * Recalculate the expiration date
263
             *
264
             * If the $tagsItem does not have
265
             * any cache item references left
266
             * then remove it from tagsItems index
267
             */
268
            if (count($data)) {
269
                $tagsItem->expiresAt(max($data));
270
                $this->driverWrite($tagsItem);
1 ignored issue
show
Bug introduced by
The method driverWrite() does not exist on phpFastCache\Cache\DriverBaseTrait. Did you maybe mean driverWriteTags()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
271
            } else {
272
                $this->driverDelete($tagsItem);
273
            }
274
        }
275
276
        return true;
277
    }
278
279
    /**
280
     * @param $key
281
     * @return string
282
     */
283
    public function getTagKey($key)
284
    {
285
        return self::DRIVER_TAGS_KEY_PREFIX . $key;
286
    }
287
288
    /**
289
     * @param $key
290
     * @return string
291
     */
292
    public function getTagKeys(array $keys)
293
    {
294
        foreach ($keys as &$key) {
295
            $key = $this->getTagKey($key);
296
        }
297
298
        return $keys;
299
    }
300
301
    /**
302
     * @param string $optionName
303
     * @param mixed $optionValue
304
     * @return bool
305
     * @throws \InvalidArgumentException
306
     */
307
    public static function isValidOption($optionName, $optionValue)
1 ignored issue
show
Unused Code introduced by
The parameter $optionValue is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
308
    {
309
        if(!is_string($optionName))
310
        {
311
            throw new \InvalidArgumentException('$optionName must be a string');
312
        }
313
        return true;
314
    }
315
316
    /**
317
     * @return array
318
     */
319
    public static function getRequiredOptions()
320
    {
321
        return [];
322
    }
323
324
    /**
325
     * @return array
326
     */
327
    public static function getValidOptions()
328
    {
329
        return [];
330
    }
331
}