LocalStorage   A
last analyzed

Complexity

Total Complexity 17

Size/Duplication

Total Lines 166
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 17
eloc 47
dl 0
loc 166
rs 10
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 17 2
A write() 0 11 1
A destroy() 0 9 2
A gc() 0 17 4
A close() 0 3 1
A read() 0 9 3
A getFileName() 0 3 1
A updateTimestamp() 0 9 1
A getSessionFile() 0 8 1
A validateId() 0 4 1
1
<?php
2
3
/**
4
 * Platine Session
5
 *
6
 * Platine Session is the lightweight implementation of php native
7
 * session handler interface
8
 *
9
 * This content is released under the MIT License (MIT)
10
 *
11
 * Copyright (c) 2020 Platine Session
12
 *
13
 * Permission is hereby granted, free of charge, to any person obtaining a copy
14
 * of this software and associated documentation files (the "Software"), to deal
15
 * in the Software without restriction, including without limitation the rights
16
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
 * copies of the Software, and to permit persons to whom the Software is
18
 * furnished to do so, subject to the following conditions:
19
 *
20
 * The above copyright notice and this permission notice shall be included in all
21
 * copies or substantial portions of the Software.
22
 *
23
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
 * SOFTWARE.
30
 */
31
32
/**
33
 *  @file LocalStorage.php
34
 *
35
 *  The Cache Driver using file system to manage the cache data
36
 *
37
 *  @package    Platine\Session\Storage
38
 *  @author Platine Developers Team
39
 *  @copyright  Copyright (c) 2020
40
 *  @license    http://opensource.org/licenses/MIT  MIT License
41
 *  @link   https://www.platine-php.com
42
 *  @version 1.0.0
43
 *  @filesource
44
 */
45
46
declare(strict_types=1);
47
48
namespace Platine\Session\Storage;
49
50
use Platine\Filesystem\DirectoryInterface;
51
use Platine\Filesystem\FileInterface;
52
use Platine\Filesystem\Filesystem;
53
use Platine\Session\Configuration;
54
use Platine\Session\Exception\FileSessionHandlerException;
55
use Platine\Stdlib\Helper\Path;
56
use Platine\Stdlib\Helper\Str;
57
use SessionHandlerInterface;
58
59
/**
60
 * @class LocalStorage
61
 * @package Platine\Session\Storage
62
 */
63
class LocalStorage extends AbstractStorage
64
{
65
     /**
66
     * The directory to use to save files
67
     * @var DirectoryInterface
68
     */
69
    protected DirectoryInterface $directory;
70
71
    /**
72
     * The file system instance
73
     * @var Filesystem
74
     */
75
    protected Filesystem $filesystem;
76
77
    /**
78
     * Create new instance
79
     * @param Filesystem $filesystem
80
     * @param Configuration|null $config
81
     * @throws FileSessionHandlerException
82
     */
83
    public function __construct(Filesystem $filesystem, ?Configuration $config = null)
84
    {
85
        parent::__construct($config);
86
87
        $path = $this->config->get('storages.file.path');
88
        $filePath = Path::normalizePath($path, true);
89
        $directory = $filesystem->directory($filePath);
90
91
        if ($directory->exists() === false) {
92
            throw new FileSessionHandlerException(sprintf(
93
                'The directory [%s] does not exist',
94
                $directory->getPath()
95
            ));
96
        }
97
98
        $this->filesystem = $filesystem;
99
        $this->directory = $directory;
100
    }
101
102
    /**
103
     * {@inheritdoc}
104
     * @see SessionHandlerInterface
105
     */
106
    public function read(string $sid): string|false
107
    {
108
        $file = $this->getSessionFile($sid);
109
110
        if ($file->exists() === false || time() > $file->getMtime()) {
111
            return '';
112
        }
113
114
        return $file->read();
115
    }
116
117
    /**
118
     * {@inheritdoc}
119
     * @see SessionHandlerInterface
120
     */
121
    public function write(string $sid, string $data): bool
122
    {
123
        $file = $this->getSessionFile($sid);
124
        $file->write($data);
125
126
        /** @var int */
127
        $expireAt = time() + (int) $this->config->get('ttl');
128
129
        $file->touch($expireAt);
130
131
        return true;
132
    }
133
134
    /**
135
     * {@inheritdoc}
136
     * @see SessionHandlerInterface
137
     */
138
    public function destroy(string $sid): bool
139
    {
140
        $file = $this->getSessionFile($sid);
141
142
        if ($file->exists()) {
143
            $file->delete();
144
        }
145
146
        return true;
147
    }
148
149
    /**
150
     * {@inheritdoc}
151
     * @see SessionHandlerInterface
152
     */
153
    public function close(): bool
154
    {
155
        return true;
156
    }
157
158
    /**
159
     * {@inheritdoc}
160
     * @see SessionHandlerInterface
161
     */
162
    public function gc(int $maxLifetime): bool
163
    {
164
        $files = $this->directory->read(DirectoryInterface::FILE);
165
        foreach ($files as /** @var FileInterface $file */ $file) {
166
            if (
167
                Str::startsWith(
168
                    $this->config->get('storages.file.prefix'),
169
                    $file->getName()
170
                )
171
            ) {
172
                if ($file->getMtime() + $maxLifetime < time()) {
173
                    $file->delete();
174
                }
175
            }
176
        }
177
178
        return true;
179
    }
180
181
    /**
182
     * {@inheritdoc}
183
     * @see SessionUpdateTimestampHandlerInterface
184
     */
185
    public function updateTimestamp(string $sid, string $data): bool
186
    {
187
        $file = $this->getSessionFile($sid);
188
        /** @var int */
189
        $expireAt = time() + (int) $this->config->get('ttl');
190
191
        $file->touch($expireAt);
192
193
        return true;
194
    }
195
196
    /**
197
     * {@inheritdoc}
198
     * @see SessionUpdateTimestampHandlerInterface
199
     */
200
    public function validateId(string $sid): bool
201
    {
202
        return $this->getSessionFile($sid)
203
                    ->exists();
204
    }
205
206
    /**
207
     * Return the file session
208
     * @param string $sid
209
     * @return FileInterface
210
     */
211
    protected function getSessionFile(string $sid): FileInterface
212
    {
213
        $filename = $this->getFileName($sid);
214
        $file = $this->filesystem->file(
215
            $this->directory->getPath() . $filename
216
        );
217
218
        return $file;
219
    }
220
221
    /**
222
     * Get session file name for given key
223
     * @param  string $sid
224
     * @return string  the filename
225
     */
226
    private function getFileName(string $sid): string
227
    {
228
        return sprintf('%s%s', $this->config->get('storages.file.prefix'), $sid);
229
    }
230
}
231