Passed
Push — develop ( b817d6...234651 )
by nguereza
02:05
created

LocalStorage::__construct()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 17
rs 9.9332
c 0
b 0
f 0
cc 3
nc 2
nop 2
1
<?php
2
3
/**
4
 * Platine Cache
5
 *
6
 * Platine Cache is the implementation of PSR 16 simple cache
7
 *
8
 * This content is released under the MIT License (MIT)
9
 *
10
 * Copyright (c) 2020 Platine Cache
11
 *
12
 * Permission is hereby granted, free of charge, to any person obtaining a copy
13
 * of this software and associated documentation files (the "Software"), to deal
14
 * in the Software without restriction, including without limitation the rights
15
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
 * copies of the Software, and to permit persons to whom the Software is
17
 * furnished to do so, subject to the following conditions:
18
 *
19
 * The above copyright notice and this permission notice shall be included in all
20
 * copies or substantial portions of the Software.
21
 *
22
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
 * SOFTWARE.
29
 */
30
31
/**
32
 *  @file LocalStorage.php
33
 *
34
 *  The Cache Driver using file system to manage the cache data
35
 *
36
 *  @package    Platine\Cache\Storage
37
 *  @author Platine Developers Team
38
 *  @copyright  Copyright (c) 2020
39
 *  @license    http://opensource.org/licenses/MIT  MIT License
40
 *  @link   http://www.iacademy.cf
41
 *  @version 1.0.0
42
 *  @filesource
43
 */
44
45
declare(strict_types=1);
46
47
namespace Platine\Cache\Storage;
48
49
use DateInterval;
50
use Platine\Cache\Configuration;
51
use Platine\Cache\Exception\CacheException;
52
use Platine\Cache\Exception\FilesystemStorageException;
53
use Platine\Filesystem\DirectoryInterface;
54
use Platine\Filesystem\FileInterface;
55
use Platine\Filesystem\Filesystem;
56
use Platine\Stdlib\Helper\Path;
57
use Platine\Stdlib\Helper\Str;
58
59
60
/**
61
 * Class LocalStorage
62
 * @package Platine\Cache\Storage
63
 */
64
class LocalStorage extends AbstractStorage
65
{
66
     /**
67
     * The directory to use to save cache files
68
     * @var DirectoryInterface
69
     */
70
    protected DirectoryInterface $directory;
71
72
    /**
73
     * The file system instance
74
     * @var Filesystem
75
     */
76
    protected Filesystem $filesystem;
77
78
    /**
79
     * Create new instance
80
     *
81
     * {@inheritdoc}
82
     */
83
    public function __construct(Filesystem $filesystem, ?Configuration $config = null)
84
    {
85
        parent::__construct($config);
86
87
        $this->filesystem = $filesystem;
88
89
        $filePath = Path::normalizePathDS($this->config->get('storages.file.path'), true);
0 ignored issues
show
Bug introduced by
It seems like $this->config->get('storages.file.path') can also be of type null; however, parameter $path of Platine\Stdlib\Helper\Path::normalizePathDS() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

89
        $filePath = Path::normalizePathDS(/** @scrutinizer ignore-type */ $this->config->get('storages.file.path'), true);
Loading history...
90
        $directory = $filesystem->directory($filePath);
91
        if (!$directory->exists() || !$directory->isWritable()) {
92
            throw new FilesystemStorageException(sprintf(
93
                'Cannot use file cache handler, because the directory %s does '
94
                    . 'not exist or is writable',
95
                $filePath
96
            ));
97
        }
98
99
        $this->directory = $directory;
100
    }
101
102
    /**
103
     * {@inheritdoc}
104
     */
105
    public function get(string $key, $default = null)
106
    {
107
        $file = $this->getCacheFile($key);
108
109
        if (!$file->exists() || $file->getMtime() <= time()) {
110
            return $default;
111
        }
112
113
        $data = $file->read();
114
115
        /** @var bool|string */
116
        $value = @unserialize($data);
117
118
119
        if ($value === false) {
120
            //unserialize failed
121
122
            return $default;
123
        }
124
125
126
        return $value;
127
    }
128
129
    /**
130
     * {@inheritdoc}
131
     */
132
    public function set(string $key, $value, $ttl = null): bool
133
    {
134
        if ($ttl === null) {
135
            $ttl = $this->config->get('ttl');
136
        } elseif ($ttl instanceof DateInterval) {
137
            $ttl = $this->convertDateIntervalToSeconds($ttl);
138
        } elseif (!is_int($ttl)) {
139
            throw new CacheException(sprintf(
140
                'Invalid cache TTL value expected null|int|DateInterval but got [%s]',
141
                gettype($ttl)
142
            ));
143
        }
144
        /** @var int */
145
        $expireAt = time() + $ttl;
146
        $file = $this->getCacheFile($key);
147
        $file->write(serialize($value));
148
        $file->touch($expireAt);
149
150
        return true;
151
    }
152
153
    /**
154
     * {@inheritdoc}
155
     */
156
    public function delete(string $key): bool
157
    {
158
        $file = $this->getCacheFile($key);
159
160
        if ($file->exists()) {
161
            $file->delete();
162
        }
163
164
        return true;
165
    }
166
167
    /**
168
     * {@inheritdoc}
169
     */
170
    public function clear(): bool
171
    {
172
        $files = $this->directory->read(DirectoryInterface::FILE);
173
        foreach ($files as /** @var FileInterface $file */ $file) {
174
            if (
175
                Str::startsWith(
176
                    $this->config->get('storages.file.prefix'),
0 ignored issues
show
Bug introduced by
It seems like $this->config->get('storages.file.prefix') can also be of type null; however, parameter $value of Platine\Stdlib\Helper\Str::startsWith() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

176
                    /** @scrutinizer ignore-type */ $this->config->get('storages.file.prefix'),
Loading history...
177
                    $file->getName()
178
                )
179
            ) {
180
                $file->delete();
181
            }
182
        }
183
184
        return true;
185
    }
186
187
    /**
188
     * {@inheritdoc}
189
     */
190
    public function has(string $key): bool
191
    {
192
        return $this->get($key, $this) !== $this;
193
    }
194
195
    /**
196
     * Return the file cache
197
     * @param string $key
198
     * @return FileInterface
199
     */
200
    protected function getCacheFile(string $key): FileInterface
201
    {
202
        $filename = $this->getFileName($key);
203
        $file = $this->filesystem->file(
204
            $this->directory->getPath() . DIRECTORY_SEPARATOR . $filename
205
        );
206
207
        return $file;
208
    }
209
210
    /**
211
     * Get cache file name for given key
212
     * @param  string $key
213
     * @return string      the filename
214
     */
215
    private function getFileName(string $key): string
216
    {
217
        $cleanKey = preg_replace('/[^A-Za-z0-9\.]+/', '_', $key);
218
        return sprintf('%s%s.cache', $this->config->get('storages.file.prefix'), $cleanKey);
219
    }
220
}
221