LocalStorage::validateId()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 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): int|false
163
    {
164
        $count = 0;
165
        $files = $this->directory->read(DirectoryInterface::FILE);
166
        foreach ($files as /** @var FileInterface $file */ $file) {
167
            if (
168
                Str::startsWith(
169
                    $this->config->get('storages.file.prefix'),
170
                    $file->getName()
171
                )
172
            ) {
173
                if ($file->getMtime() + $maxLifetime < time()) {
174
                    $file->delete();
175
                    $count++;
176
                }
177
            }
178
        }
179
180
        return $count;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $count returns the type integer which is incompatible with the return type mandated by SessionHandlerInterface::gc() of boolean.

In the issue above, the returned value is violating the contract defined by the mentioned interface.

Let's take a look at an example:

interface HasName {
    /** @return string */
    public function getName();
}

class Name {
    public $name;
}

class User implements HasName {
    /** @return string|Name */
    public function getName() {
        return new Name('foo'); // This is a violation of the ``HasName`` interface
                                // which only allows a string value to be returned.
    }
}
Loading history...
181
    }
182
183
    /**
184
     * {@inheritdoc}
185
     * @see SessionUpdateTimestampHandlerInterface
186
     */
187
    public function updateTimestamp(string $sid, string $data): bool
188
    {
189
        $file = $this->getSessionFile($sid);
190
        /** @var int */
191
        $expireAt = time() + (int) $this->config->get('ttl');
192
193
        $file->touch($expireAt);
194
195
        return true;
196
    }
197
198
    /**
199
     * {@inheritdoc}
200
     * @see SessionUpdateTimestampHandlerInterface
201
     */
202
    public function validateId(string $sid): bool
203
    {
204
        return $this->getSessionFile($sid)
205
                    ->exists();
206
    }
207
208
    /**
209
     * Return the file session
210
     * @param string $sid
211
     * @return FileInterface
212
     */
213
    protected function getSessionFile(string $sid): FileInterface
214
    {
215
        $filename = $this->getFileName($sid);
216
        $file = $this->filesystem->file(
217
            $this->directory->getPath() . $filename
218
        );
219
220
        return $file;
221
    }
222
223
    /**
224
     * Get session file name for given key
225
     * @param  string $sid
226
     * @return string  the filename
227
     */
228
    private function getFileName(string $sid): string
229
    {
230
        return sprintf('%s%s', $this->config->get('storages.file.prefix'), $sid);
231
    }
232
}
233