Passed
Pull Request — master (#85)
by
unknown
04:04 queued 01:04
created

JibitCache::isCached()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 2 Features 2
Metric Value
cc 2
eloc 3
c 4
b 2
f 2
nc 2
nop 1
dl 0
loc 5
rs 10
1
<?php
2
namespace Shetabit\Multipay\Drivers\Jibit;
3
4
/**
5
 * Simple Cache class
6
 * API Documentation: https://github.com/cosenary/Simple-PHP-Cache
7
 *
8
 * @author Christian Metz
9
 * @since 22.12.2011
10
 * @copyright Christian Metz - MetzWeb Networks
11
 * @version 1.6
12
 * @license BSD http://www.opensource.org/licenses/bsd-license.php
13
 */
14
15
class JibitCache
16
{
17
18
    /**
19
     * The path to the cache file folder
20
     *
21
     * @var string
22
     */
23
    private $_cachepath = 'cache/';
24
25
    /**
26
     * The name of the default cache file
27
     *
28
     * @var string
29
     */
30
    private $_cachename = 'default';
31
32
    /**
33
     * The cache file extension
34
     *
35
     * @var string
36
     */
37
    private $_extension = '.cache';
38
39
    /**
40
     * Default constructor
41
     *
42
     * @param string|array [optional] $config
43
     * @return void
44
     */
45
    public function __construct($config = null)
46
    {
47
        if (true === isset($config)) {
48
            if (is_string($config)) {
49
                $this->setCache($config);
50
            } elseif (is_array($config)) {
51
                $this->setCache($config['name']);
52
                $this->setCachePath($config['path']);
53
                $this->setExtension($config['extension']);
54
            }
55
        }
56
    }
57
58
    /**
59
     * Cache name Setter
60
     *
61
     * @param string $name
62
     * @return object
63
     */
64
    public function setCache($name)
65
    {
66
        $this->_cachename = $name;
67
        return $this;
68
    }
69
70
    /**
71
     * Check whether data accociated with a key
72
     *
73
     * @param string $key
74
     * @return boolean
75
     */
76
    public function isCached($key)
77
    {
78
        if (false != $this->_loadCache()) {
79
            $cachedData = $this->_loadCache();
80
            return isset($cachedData[$key]['data']);
81
        }
82
    }
83
84
    /**
85
     * Load appointed cache
86
     *
87
     * @return mixed
88
     */
89
    private function _loadCache()
90
    {
91
        if (true === file_exists($this->getCacheDir())) {
92
            $file = file_get_contents($this->getCacheDir());
93
            return json_decode($file, true);
94
        } else {
95
            return false;
96
        }
97
    }
98
99
    /**
100
     * Get the cache directory path
101
     *
102
     * @return string
103
     */
104
    public function getCacheDir()
105
    {
106
        if (true === $this->_checkCacheDir()) {
0 ignored issues
show
introduced by
The condition true === $this->_checkCacheDir() is always true.
Loading history...
107
            $filename = $this->getCache();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $filename is correct as $this->getCache() targeting Shetabit\Multipay\Driver...\JibitCache::getCache() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
108
            $filename = preg_replace('/[^0-9a-z\.\_\-]/i', '', strtolower($filename));
0 ignored issues
show
Bug introduced by
$filename of type void is incompatible with the type string expected by parameter $string of strtolower(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

108
            $filename = preg_replace('/[^0-9a-z\.\_\-]/i', '', strtolower(/** @scrutinizer ignore-type */ $filename));
Loading history...
109
            return $this->getCachePath() . $this->_getHash($filename) . $this->getExtension();
110
        }
111
    }
112
113
    /**
114
     * Check if a writable cache directory exists and if not create a new one
115
     *
116
     * @return boolean
117
     */
118
    private function _checkCacheDir()
119
    {
120
        if (!is_dir($this->getCachePath()) && !mkdir($this->getCachePath(), 0775, true)) {
121
            throw new \Exception('Unable to create cache directory ' . $this->getCachePath());
122
        } elseif (!is_readable($this->getCachePath()) || !is_writable($this->getCachePath())) {
123
            if (!chmod($this->getCachePath(), 0775)) {
124
                throw new \Exception($this->getCachePath() . ' must be readable and writeable');
125
            }
126
        }
127
        return true;
128
    }
129
130
    /**
131
     * Cache path Getter
132
     *
133
     * @return string
134
     */
135
    public function getCachePath()
136
    {
137
        return $this->_cachepath;
138
    }
139
140
    /**
141
     * Cache path Setter
142
     *
143
     * @param string $path
144
     * @return object
145
     */
146
    public function setCachePath($path)
147
    {
148
        $this->_cachepath = $path;
149
        return $this;
150
    }
151
152
    /**
153
     * Cache name Getter
154
     *
155
     * @return void
156
     */
157
    public function getCache()
158
    {
159
        return $this->_cachename;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->_cachename returns the type string which is incompatible with the documented return type void.
Loading history...
160
    }
161
162
    /**
163
     * Get the filename hash
164
     *
165
     * @return string
166
     */
167
    private function _getHash($filename)
168
    {
169
        return sha1($filename);
170
    }
171
172
    /**
173
     * Cache file extension Getter
174
     *
175
     * @return string
176
     */
177
    public function getExtension()
178
    {
179
        return $this->_extension;
180
    }
181
182
    /**
183
     * Cache file extension Setter
184
     *
185
     * @param string $ext
186
     * @return object
187
     */
188
    public function setExtension($ext)
189
    {
190
        $this->_extension = $ext;
191
        return $this;
192
    }
193
194
    /**
195
     * Store data in the cache
196
     *
197
     * @param string $key
198
     * @param mixed $data
199
     * @param integer [optional] $expiration
200
     * @return object
201
     */
202
    public function store($key, $data, $expiration = 0)
203
    {
204
        $storeData = array(
205
            'time' => time(),
206
            'expire' => $expiration,
207
            'data' => serialize($data)
208
        );
209
        $dataArray = $this->_loadCache();
210
        if (true === is_array($dataArray)) {
211
            $dataArray[$key] = $storeData;
212
        } else {
213
            $dataArray = array($key => $storeData);
214
        }
215
        $cacheData = json_encode($dataArray);
216
        file_put_contents($this->getCacheDir(), $cacheData);
217
        return $this;
218
    }
219
220
    /**
221
     * Retrieve cached data by its key
222
     *
223
     * @param string $key
224
     * @param boolean [optional] $timestamp
225
     * @return string
226
     */
227
    public function retrieve($key, $timestamp = false)
228
    {
229
        $cachedData = $this->_loadCache();
230
        (false === $timestamp) ? $type = 'data' : $type = 'time';
231
        if (!isset($cachedData[$key][$type])) {
232
            return null;
233
        }
234
        return unserialize($cachedData[$key][$type]);
235
    }
236
237
    /**
238
     * Retrieve all cached data
239
     *
240
     * @param boolean [optional] $meta
241
     * @return array
242
     */
243
    public function retrieveAll($meta = false)
244
    {
245
        if ($meta === false) {
246
            $results = array();
247
            $cachedData = $this->_loadCache();
248
            if ($cachedData) {
249
                foreach ($cachedData as $k => $v) {
250
                    $results[$k] = unserialize($v['data']);
251
                }
252
            }
253
            return $results;
254
        } else {
255
            return $this->_loadCache();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->_loadCache() could also return false which is incompatible with the documented return type array. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
256
        }
257
    }
258
259
    /**
260
     * Erase cached entry by its key
261
     *
262
     * @param string $key
263
     * @return object
264
     */
265
    public function erase($key)
266
    {
267
        $cacheData = $this->_loadCache();
268
        if (true === is_array($cacheData)) {
269
            if (true === isset($cacheData[$key])) {
270
                unset($cacheData[$key]);
271
                $cacheData = json_encode($cacheData);
272
                file_put_contents($this->getCacheDir(), $cacheData);
273
            } else {
274
                throw new \Exception("Error: erase() - Key '{$key}' not found.");
275
            }
276
        }
277
        return $this;
278
    }
279
280
    /**
281
     * Erase all expired entries
282
     *
283
     * @return integer
284
     */
285
    public function eraseExpired()
286
    {
287
        $cacheData = $this->_loadCache();
288
        if (true === is_array($cacheData)) {
289
            $counter = 0;
290
            foreach ($cacheData as $key => $entry) {
291
                if (true === $this->_checkExpired($entry['time'], $entry['expire'])) {
292
                    unset($cacheData[$key]);
293
                    $counter++;
294
                }
295
            }
296
            if ($counter > 0) {
297
                $cacheData = json_encode($cacheData);
298
                file_put_contents($this->getCacheDir(), $cacheData);
299
            }
300
            return $counter;
301
        }
302
    }
303
304
    /**
305
     * Check whether a timestamp is still in the duration
306
     *
307
     * @param integer $timestamp
308
     * @param integer $expiration
309
     * @return boolean
310
     */
311
    private function _checkExpired($timestamp, $expiration)
312
    {
313
        $result = false;
314
        if ($expiration !== 0) {
315
            $timeDiff = time() - $timestamp;
316
            ($timeDiff > $expiration) ? $result = true : $result = false;
317
        }
318
        return $result;
319
    }
320
321
    /**
322
     * Erase all cached entries
323
     *
324
     * @return object
325
     */
326
    public function eraseAll()
327
    {
328
        $cacheDir = $this->getCacheDir();
329
        if (true === file_exists($cacheDir)) {
330
            $cacheFile = fopen($cacheDir, 'w');
331
            fclose($cacheFile);
332
        }
333
        return $this;
334
    }
335
}
336