Passed
Pull Request — master (#85)
by
unknown
03:35 queued 34s
created

JibitCache::retrieveAll()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
cc 4
eloc 9
c 2
b 0
f 2
nc 3
nop 1
dl 0
loc 13
rs 9.9666
1
<?php
2
namespace Shetabit\Multipay\Drivers\Jibit;
3
/**
4
 * Simple Cache class
5
 * API Documentation: https://github.com/cosenary/Simple-PHP-Cache
6
 *
7
 * @author Christian Metz
8
 * @since 22.12.2011
9
 * @copyright Christian Metz - MetzWeb Networks
10
 * @version 1.6
11
 * @license BSD http://www.opensource.org/licenses/bsd-license.php
12
 */
13
14
class JibitCache
15
{
16
17
    /**
18
     * The path to the cache file folder
19
     *
20
     * @var string
21
     */
22
    private $_cachepath = 'cache/';
23
24
    /**
25
     * The name of the default cache file
26
     *
27
     * @var string
28
     */
29
    private $_cachename = 'default';
30
31
    /**
32
     * The cache file extension
33
     *
34
     * @var string
35
     */
36
    private $_extension = '.cache';
37
38
    /**
39
     * Default constructor
40
     *
41
     * @param string|array [optional] $config
42
     * @return void
43
     */
44
    public function __construct($config = null)
45
    {
46
        if (true === isset($config)) {
47
            if (is_string($config)) {
48
                $this->setCache($config);
49
            } else if (is_array($config)) {
50
                $this->setCache($config['name']);
51
                $this->setCachePath($config['path']);
52
                $this->setExtension($config['extension']);
53
            }
54
        }
55
    }
56
57
    /**
58
     * Cache name Setter
59
     *
60
     * @param string $name
61
     * @return object
62
     */
63
    public function setCache($name)
64
    {
65
        $this->_cachename = $name;
66
        return $this;
67
    }
68
69
    /**
70
     * Check whether data accociated with a key
71
     *
72
     * @param string $key
73
     * @return boolean
74
     */
75
    public function isCached($key)
76
    {
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])) return null;
232
        return unserialize($cachedData[$key][$type]);
233
    }
234
235
    /**
236
     * Retrieve all cached data
237
     *
238
     * @param boolean [optional] $meta
239
     * @return array
240
     */
241
    public function retrieveAll($meta = false)
242
    {
243
        if ($meta === false) {
244
            $results = array();
245
            $cachedData = $this->_loadCache();
246
            if ($cachedData) {
247
                foreach ($cachedData as $k => $v) {
248
                    $results[$k] = unserialize($v['data']);
249
                }
250
            }
251
            return $results;
252
        } else {
253
            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...
254
        }
255
    }
256
257
    /**
258
     * Erase cached entry by its key
259
     *
260
     * @param string $key
261
     * @return object
262
     */
263
    public function erase($key)
264
    {
265
        $cacheData = $this->_loadCache();
266
        if (true === is_array($cacheData)) {
267
            if (true === isset($cacheData[$key])) {
268
                unset($cacheData[$key]);
269
                $cacheData = json_encode($cacheData);
270
                file_put_contents($this->getCacheDir(), $cacheData);
271
            } else {
272
                throw new \Exception("Error: erase() - Key '{$key}' not found.");
273
            }
274
        }
275
        return $this;
276
    }
277
278
    /**
279
     * Erase all expired entries
280
     *
281
     * @return integer
282
     */
283
    public function eraseExpired()
284
    {
285
        $cacheData = $this->_loadCache();
286
        if (true === is_array($cacheData)) {
287
            $counter = 0;
288
            foreach ($cacheData as $key => $entry) {
289
                if (true === $this->_checkExpired($entry['time'], $entry['expire'])) {
290
                    unset($cacheData[$key]);
291
                    $counter++;
292
                }
293
            }
294
            if ($counter > 0) {
295
                $cacheData = json_encode($cacheData);
296
                file_put_contents($this->getCacheDir(), $cacheData);
297
            }
298
            return $counter;
299
        }
300
    }
301
302
    /**
303
     * Check whether a timestamp is still in the duration
304
     *
305
     * @param integer $timestamp
306
     * @param integer $expiration
307
     * @return boolean
308
     */
309
    private function _checkExpired($timestamp, $expiration)
310
    {
311
        $result = false;
312
        if ($expiration !== 0) {
313
            $timeDiff = time() - $timestamp;
314
            ($timeDiff > $expiration) ? $result = true : $result = false;
315
        }
316
        return $result;
317
    }
318
319
    /**
320
     * Erase all cached entries
321
     *
322
     * @return object
323
     */
324
    public function eraseAll()
325
    {
326
        $cacheDir = $this->getCacheDir();
327
        if (true === file_exists($cacheDir)) {
328
            $cacheFile = fopen($cacheDir, 'w');
329
            fclose($cacheFile);
330
        }
331
        return $this;
332
    }
333
334
}
335