Completed
Branch final (ad8b8d)
by Georges
03:08 queued 28s
created

DriverBaseTrait::isPHPModule()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 12
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 default options, this will be merge to Driver's Options
29
     */
30
    protected $config = [];
31
32
    /**
33
     * @var bool
34
     */
35
    protected $fallback = false;
36
37
    /**
38
     * @var mixed Instance of driver service
39
     */
40
    protected $instance;
41
42
    /**
43
     * @param $keyword
44
     * @return string
45
     */
46
    protected function encodeFilename($keyword)
47
    {
48
        return md5($keyword);
49
    }
50
51
    /**
52
     * @param $config_name
53
     * @param string $value
54
     */
55
    public function setup($config_name, $value = '')
56
    {
57
        /**
58
         * Config for class
59
         */
60
        if (is_array($config_name)) {
61
            $this->config = array_merge($this->config, $config_name);
62
        } else {
63
            $this->config[ $config_name ] = $value;
64
        }
65
    }
66
67
    /**
68
     * @return array
69
     */
70
    public function getConfig()
71
    {
72
        return $this->config;
73
    }
74
75
    /**
76
     * @param $file
77
     * @return string
78
     * @throws \Exception
79
     */
80
    protected function readfile($file)
81
    {
82
        if (function_exists('file_get_contents')) {
83
            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...
84
        } else {
85
            $string = '';
86
87
            $file_handle = @fopen($file, 'r');
88
            if (!$file_handle) {
89
                throw new phpFastCacheDriverException("Can't Read File", 96);
90
91
            }
92
            while (!feof($file_handle)) {
93
                $line = fgets($file_handle);
94
                $string .= $line;
95
            }
96
            fclose($file_handle);
97
98
            return $string;
99
        }
100
    }
101
102
    /**
103
     * Encode data types such as object/array
104
     * for driver that does not support
105
     * non-scalar value
106
     * @param $data
107
     * @return string
108
     */
109
    protected function encode($data)
110
    {
111
        return serialize($data);
112
    }
113
114
    /**
115
     * Decode data types such as object/array
116
     * for driver that does not support
117
     * non-scalar value
118
     * @param $value
119
     * @return mixed
120
     */
121
    protected function decode($value)
122
    {
123
        return @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...
124
    }
125
126
    /**
127
     * Check phpModules or CGI
128
     * @return bool
129
     */
130
    protected function isPHPModule()
131
    {
132
        if (PHP_SAPI === 'apache2handler') {
133
            return true;
134
        } else {
135
            if (strpos(PHP_SAPI, 'handler') !== false) {
136
                return true;
137
            }
138
        }
139
140
        return false;
141
    }
142
143
144
    /**
145
     * @param $class
146
     * @return bool
147
     */
148
    protected function isExistingDriver($class)
149
    {
150
        return class_exists("\\phpFastCache\\Drivers\\{$class}");
151
    }
152
153
154
    /**
155
     * @param $tag
156
     * @return string
157
     */
158
    protected function _getTagName($tag)
159
    {
160
        return "__tag__" . $tag;
161
    }
162
163
    /**
164
     * @param \phpFastCache\Cache\ExtendedCacheItemInterface $item
165
     * @return array
166
     */
167
    public function driverPreWrap(ExtendedCacheItemInterface $item)
168
    {
169
        return [
170
          self::DRIVER_DATA_WRAPPER_INDEX => $item->get(),
171
          self::DRIVER_TIME_WRAPPER_INDEX => $item->getExpirationDate(),
172
          self::DRIVER_TAGS_WRAPPER_INDEX => $item->getTags(),
173
        ];
174
    }
175
176
    /**
177
     * @param array $wrapper
178
     * @return mixed
179
     */
180
    public function driverUnwrapData(array $wrapper)
181
    {
182
        return $wrapper[ self::DRIVER_DATA_WRAPPER_INDEX ];
183
    }
184
185
    /**
186
     * @param array $wrapper
187
     * @return mixed
188
     */
189
    public function driverUnwrapTags(array $wrapper)
190
    {
191
        return $wrapper[ self::DRIVER_TAGS_WRAPPER_INDEX ];
192
    }
193
194
195
    /**
196
     * @param array $wrapper
197
     * @return \DateTime
198
     */
199
    public function driverUnwrapTime(array $wrapper)
200
    {
201
        return $wrapper[ self::DRIVER_TIME_WRAPPER_INDEX ];
202
    }
203
204
    /**
205
     * @return string
206
     */
207
    public function getDriverName()
208
    {
209
        static $driverName;
210
211
        return ($driverName ?: $driverName = ucfirst(substr(strrchr((new \ReflectionObject($this))->getNamespaceName(), '\\'), 1)));
212
    }
213
214
    /**
215
     * @param \phpFastCache\Cache\ExtendedCacheItemInterface $item
216
     * @return bool
217
     */
218
    public function driverWriteTags(ExtendedCacheItemInterface $item)
219
    {
220
        $tagsItems = $this->getItems($this->getTagKeys($item->getTags()));
221
222
        foreach ($tagsItems as $tagsItem) {
223
            $data = $tagsItem->get();
224
            $expTimestamp = $item->getExpirationDate()->getTimestamp();
225
226
            /**
227
             * Using the key will
228
             * avoid to use array_unique
229
             * that has slow performances
230
             */
231
232
            $tagsItem->set(array_merge((array) $data, [$item->getKey() => $expTimestamp]));
233
234
            /**
235
             * Set the expiration date
236
             * of the $tagsItem based
237
             * on the older $item
238
             * expiration date
239
             */
240
            if ($expTimestamp > $tagsItem->getExpirationDate()->getTimestamp()) {
241
                $tagsItem->expiresAt($item->getExpirationDate());
242
            }
243
            $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...
244
        }
245
246
        /**
247
         * Also update removed tags to
248
         * keep the index up to date
249
         */
250
        $tagsItems = $this->getItems($this->getTagKeys($item->getRemovedTags()));
251
252
        foreach ($tagsItems as $tagsItem) {
253
            $data = (array) $tagsItem->get();
254
255
            unset($data[ $item->getKey() ]);
256
            $tagsItem->set($data);
257
258
            /**
259
             * Recalculate the expiration date
260
             *
261
             * If the $tagsItem does not have
262
             * any cache item references left
263
             * then remove it from tagsItems index
264
             */
265
            if (count($data)) {
266
                $tagsItem->expiresAt(max($data));
267
                $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...
268
            } else {
269
                $this->driverDelete($tagsItem);
270
            }
271
        }
272
273
        return true;
274
    }
275
276
    /**
277
     * @param $key
278
     * @return string
279
     */
280
    public function getTagKey($key)
281
    {
282
        return self::DRIVER_TAGS_KEY_PREFIX . $key;
283
    }
284
285
    /**
286
     * @param $key
287
     * @return string
288
     */
289
    public function getTagKeys(array $keys)
290
    {
291
        foreach ($keys as &$key) {
292
            $key = $this->getTagKey($key);
293
        }
294
295
        return $keys;
296
    }
297
298
    /**
299
     * @param string $optionName
300
     * @param mixed $optionValue
301
     * @return bool
302
     * @throws \InvalidArgumentException
303
     */
304
    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...
305
    {
306
        if (!is_string($optionName)) {
307
            throw new \InvalidArgumentException('$optionName must be a string');
308
        }
309
310
        return true;
311
    }
312
313
    /**
314
     * @return array
315
     */
316
    public static function getRequiredOptions()
317
    {
318
        return [];
319
    }
320
321
    /**
322
     * @return array
323
     */
324
    public static function getValidOptions()
325
    {
326
        return [];
327
    }
328
}