Completed
Push — master ( b03125...a02e70 )
by Mikael
03:05
created

FileCache::prune()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Anax\Cache;
4
5
/**
6
 * File based cache in line with PSR-3.
7
 *
8
 */
9
class FileCache
10
{
11
12
13
14
    /**
15
     * Create a key to use for the cache.
16
     *
17
     * @param string $class name of the class, including
18
     *                      namespace.
19
     * @param string $id    unique id for item in each class.
20
     *
21
     * @return string the filename.
22
     */
23
    public function createKey($class, $id)
24
    {
25
        return str_replace('\\', '-', $class) . '#' . $id;
26
    }
27
28
29
30
    /**
31
     * Generate a filename for the cached object.
32
     *
33
     * @param string $key to the cached object.
34
     *
35
     * @return string the filename.
36
     */
37
    public function filename($key)
38
    {
39
        return $this->config['basepath'] . '/' . $key;
0 ignored issues
show
Bug Best Practice introduced by
The property config does not exist on Anax\Cache\FileCache. Did you maybe forget to declare it?
Loading history...
40
    }
41
42
43
44
    /**
45
     * Get an item from the cache if available.
46
     *
47
     * @param string  $key to the cached object.
48
     * @param boolean $age check the age or not, defaults to
49
     *                     false.
50
     *
51
     * @return mixed the cached object or false if it has aged
52
     *               or null if it does not exists.
53
     */
54
    public function get($key, $age = false)
55
    {
56
        $file = $this->filename($key);
57
58
        if (is_file($file)) {
59
            if ($age) {
60
                $age = filemtime($file) + $this->config['age'] > time();
0 ignored issues
show
Bug Best Practice introduced by
The property config does not exist on Anax\Cache\FileCache. Did you maybe forget to declare it?
Loading history...
61
            }
62
63
            if (!$age) {
64
                // json
65
                // text
66
                return unserialize(file_get_contents($file));
67
            }
68
            return false;
69
        }
70
        return null;
71
    }
72
73
74
75
    /**
76
     * Put an item to the cache.
77
     *
78
     * @param string $key  to the cached object.
79
     * @param mixed  $item the object to be cached.
80
     *
81
     * @throws Exception if failing to write to cache.
82
     *
83
     * @return void
84
     */
85
    public function put($key, $item)
86
    {
87
        $file = $this->filename($key);
88
89
        // json
90
        // text
91
        if (!file_put_contents($file, serialize($item))) {
92
            throw new \Exception(
93
                t("Failed writing cache object '!key'.", [
0 ignored issues
show
Bug introduced by
The function t was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

93
                /** @scrutinizer ignore-call */ 
94
                t("Failed writing cache object '!key'.", [
Loading history...
94
                    '!key' => $key
95
                ])
96
            );
97
        }
98
    }
99
100
101
102
    /**
103
     * Prune a item from cache.
104
     *
105
     * @param string $key to the cached object.
106
     *
107
     * @return void
108
     */
109
    public function prune($key)
110
    {
111
        @unlink($this->filename($key));
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

111
        /** @scrutinizer ignore-unhandled */ @unlink($this->filename($key));

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
112
    }
113
114
115
116
    /**
117
     * Prune all items from cache.
118
     *
119
     * @return int number of items removed.
120
     */
121
    public function pruneAll()
122
    {
123
        $files = glob($this->config['basepath'] . '/*');
0 ignored issues
show
Bug Best Practice introduced by
The property config does not exist on Anax\Cache\FileCache. Did you maybe forget to declare it?
Loading history...
124
        $items = count($files);
125
        array_map('unlink', $files);
126
        return $items;
127
    }
128
}
129