• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

aplus-framework / session / 45629379483

23 Nov 2026 08:40PM UTC coverage: 93.868%. Remained the same
45629379483

push

github

natanfelles
Add SaveHandler::create_sid method

1 of 1 new or added line in 1 file covered. (100.0%)

1 existing line in 1 file now uncovered.

995 of 1060 relevant lines covered (93.87%)

43.32 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.67
/src/SaveHandler.php
1
<?php declare(strict_types=1);
2
/*
3
 * This file is part of Aplus Framework Session Library.
4
 *
5
 * (c) Natan Felles <natanfelles@gmail.com>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
namespace Framework\Session;
11

12
use Framework\Log\Logger;
13
use Framework\Log\LogLevel;
14
use RuntimeException;
15
use SensitiveParameter;
16

17
/**
18
 * Class SaveHandler.
19
 *
20
 * @see https://www.php.net/manual/en/class.sessionhandler.php
21
 * @see https://gist.github.com/mindplay-dk/623bdd50c1b4c0553cd3
22
 * @see https://www.cloudways.com/blog/setup-redis-as-session-handler-php/#sessionlifecycle
23
 *
24
 * @package session
25
 */
26
abstract class SaveHandler implements \SessionHandlerInterface, \SessionUpdateTimestampHandlerInterface
27
{
28
    /**
29
     * The configurations used by the save handler.
30
     *
31
     * @var array<string,mixed>
32
     */
33
    protected array $config;
34
    /**
35
     * The current data fingerprint.
36
     *
37
     * @var string
38
     */
39
    protected string $fingerprint;
40
    /**
41
     * The lock id or false if is not locked.
42
     *
43
     * @var false|string
44
     */
45
    protected false | string $lockId = false;
46
    /**
47
     * Tells if the session exists (if was read).
48
     *
49
     * @var bool
50
     */
51
    protected bool $sessionExists = false;
52
    /**
53
     * The current session ID.
54
     *
55
     * @var string|null
56
     */
57
    protected ?string $sessionId;
58
    /**
59
     * The Logger instance or null if it was not set.
60
     *
61
     * @var Logger|null
62
     */
63
    protected ?Logger $logger;
64
    /**
65
     * It says that the handler object was set with an externally created object.
66
     *
67
     * If this is true, the handler object should not be changed or removed (in the close method).
68
     *
69
     * Some functions, such as `session_regenerate_id`, call the close method and then open again!
70
     *
71
     * @var bool
72
     */
73
    protected bool $setByExternal = false;
74

75
    /**
76
     * SessionSaveHandler constructor.
77
     *
78
     * @param array<string,mixed> $config
79
     * @param Logger|null $logger
80
     */
81
    public function __construct(
82
        #[SensitiveParameter]
83
        array $config = [],
84
        ?Logger $logger = null
85
    ) {
86
        $this->prepareConfig($config);
259 ✔
87
        $this->logger = $logger;
259 ✔
88
    }
89

90
    /**
91
     * Prepare configurations to be used by the save handler.
92
     *
93
     * @param array<string,mixed> $config Custom configs
94
     *
95
     * @codeCoverageIgnore
96
     */
97
    protected function prepareConfig(#[SensitiveParameter] array $config) : void
98
    {
99
        $this->config = $config;
100
    }
101

102
    /**
103
     * @return array<string,mixed>
104
     */
105
    public function getConfig() : array
106
    {
107
        return $this->config;
5 ✔
108
    }
109

110
    /**
111
     * Log a message if the Logger is set.
112
     *
113
     * @param string $message The message to log
114
     * @param LogLevel $level The log level
115
     */
116
    protected function log(string $message, LogLevel $level = LogLevel::ERROR) : void
117
    {
118
        $this->logger?->log($level, $message);
103 ✔
119
    }
120

121
    /**
122
     * Set the data fingerprint.
123
     *
124
     * @param string $data The data to set the new fingerprint
125
     */
126
    protected function setFingerprint(string $data) : void
127
    {
128
        $this->fingerprint = $this->makeFingerprint($data);
262 ✔
129
    }
130

131
    /**
132
     * Make the fingerprint value.
133
     *
134
     * @param string $data The data to get the fingerprint
135
     *
136
     * @return string The fingerprint hash
137
     */
138
    private function makeFingerprint(string $data) : string
139
    {
140
        return \hash('xxh3', $data);
262 ✔
141
    }
142

143
    /**
144
     * Tells if the data has the same current fingerprint.
145
     *
146
     * @param string $data The data to compare
147
     *
148
     * @return bool True if the fingerprints are the same, otherwise false
149
     */
150
    protected function hasSameFingerprint(string $data) : bool
151
    {
152
        return $this->fingerprint === $this->makeFingerprint($data);
74 ✔
153
    }
154

155
    /**
156
     * Get the maxlifetime (TTL) used by cache handlers or locking.
157
     *
158
     * NOTE: It will use the `maxlifetime` config or the ini value of
159
     * `session.gc_maxlifetime` as fallback.
160
     *
161
     * @return int The maximum lifetime of a session in seconds
162
     */
163
    protected function getMaxlifetime() : int
164
    {
165
        return (int) ($this->config['maxlifetime'] ?? \ini_get('session.gc_maxlifetime'));
127 ✔
166
    }
167

168
    /**
169
     * Get the remote IP address.
170
     *
171
     * @return string
172
     */
173
    protected function getIP() : string
174
    {
175
        return $_SERVER['REMOTE_ADDR'] ?? '';
129 ✔
176
    }
177

178
    /**
179
     * Get the HTTP User-Agent.
180
     *
181
     * @return string
182
     */
183
    protected function getUA() : string
184
    {
185
        return $_SERVER['HTTP_USER_AGENT'] ?? '';
129 ✔
186
    }
187

188
    protected function getKeySuffix() : string
189
    {
190
        $suffix = '';
195 ✔
191
        if ($this->config['match_ip']) {
195 ✔
192
            $suffix .= ':' . $this->getIP();
96 ✔
193
        }
194
        if ($this->config['match_ua']) {
195 ✔
195
            $suffix .= ':' . $this->getUA();
96 ✔
196
        }
197
        if ($suffix) {
195 ✔
198
            $suffix = \hash('xxh3', $suffix);
96 ✔
199
        }
200
        return $suffix;
195 ✔
201
    }
202

203
    public function create_sid() : string
204
    {
205
        return \session_create_id() ?: throw new RuntimeException('Unable to create a session id');
263 ✔
206
    }
207

208
    /**
209
     * Validate session id.
210
     *
211
     * @param string $id The session id
212
     *
213
     * @see https://www.php.net/manual/en/sessionupdatetimestamphandlerinterface.validateid.php
214
     * @see https://wiki.php.net/rfc/deprecations_php_8_4#sessionsid_length_and_sessionsid_bits_per_character
215
     *
216
     * @return bool Returns TRUE if the id is valid, otherwise FALSE
217
     */
218
    public function validateId($id) : bool
219
    {
220
        if (\PHP_VERSION_ID >= 80400) {
98 ✔
UNCOV
221
            return (bool) \preg_match('#\A[0-9a-f]{32}\z#', $id);
×
222
        }
223
        $bits = \ini_get('session.sid_bits_per_character') ?: 5;
98 ✔
224
        $length = \ini_get('session.sid_length') ?: 40;
98 ✔
225
        $bitsRegex = [
98 ✔
226
            4 => '[0-9a-f]',
98 ✔
227
            5 => '[0-9a-v]',
98 ✔
228
            6 => '[0-9a-zA-Z,-]',
98 ✔
229
        ];
98 ✔
230
        return isset($bitsRegex[$bits])
98 ✔
231
            && \preg_match('#\A' . $bitsRegex[$bits] . '{' . $length . '}\z#', $id);
98 ✔
232
    }
233

234
    /**
235
     * Initialize the session.
236
     *
237
     * @param string $path The path where to store/retrieve the session
238
     * @param string $name The session name
239
     *
240
     * @see https://www.php.net/manual/en/sessionhandlerinterface.open.php
241
     *
242
     * @return bool Returns TRUE on success, FALSE on failure
243
     */
244
    abstract public function open($path, $name) : bool;
245

246
    /**
247
     * Read session data.
248
     *
249
     * @param string $id The session id to read data for
250
     *
251
     * @see https://www.php.net/manual/en/sessionhandlerinterface.read.php
252
     *
253
     * @return string Returns an encoded string of the read data.
254
     * If nothing was read, it returns an empty string
255
     */
256
    abstract public function read($id) : string;
257

258
    /**
259
     * Write session data.
260
     *
261
     * @param string $id The session id
262
     * @param string $data The encoded session data. This data is the result
263
     * of the PHP internally encoding the $_SESSION superglobal to a serialized
264
     * string and passing it as this parameter.
265
     *
266
     * NOTE: Sessions can use an alternative serialization method
267
     *
268
     * @see https://www.php.net/manual/en/sessionhandlerinterface.write.php
269
     *
270
     * @return bool Returns TRUE on success, FALSE on failure
271
     */
272
    abstract public function write($id, $data) : bool;
273

274
    /**
275
     * Update the timestamp of a session.
276
     *
277
     * @param string $id The session id
278
     * @param string $data The encoded session data. This data is the result
279
     * of the PHP internally encoding the $_SESSION superglobal to a serialized
280
     * string and passing it as this parameter.
281
     *
282
     * NOTE: Sessions can use an alternative serialization method
283
     *
284
     * @see https://www.php.net/manual/en/sessionupdatetimestamphandlerinterface.updatetimestamp.php
285
     *
286
     * @return bool Returns TRUE on success, FALSE on failure
287
     */
288
    abstract public function updateTimestamp($id, $data) : bool;
289

290
    /**
291
     * Close the session.
292
     *
293
     * @see https://www.php.net/manual/en/sessionhandlerinterface.close.php
294
     *
295
     * @return bool Returns TRUE on success, FALSE on failure
296
     */
297
    abstract public function close() : bool;
298

299
    /**
300
     * Destroy a session.
301
     *
302
     * @param string $id The session ID being destroyed
303
     *
304
     * @see https://www.php.net/manual/en/sessionhandlerinterface.destroy.php
305
     *
306
     * @return bool Returns TRUE on success, FALSE on failure
307
     */
308
    abstract public function destroy($id) : bool;
309

310
    /**
311
     * Cleanup old sessions.
312
     *
313
     * @param int $max_lifetime Sessions that have not updated for
314
     * the last $maxLifetime seconds will be removed
315
     *
316
     * @see https://www.php.net/manual/en/sessionhandlerinterface.gc.php
317
     *
318
     * @return false|int Returns the number of deleted session data for success,
319
     * false for failure
320
     */
321
    abstract public function gc($max_lifetime) : false | int;
322

323
    /**
324
     * Acquire a lock for a session id.
325
     *
326
     * @param string $id The session id
327
     *
328
     * @return bool Returns TRUE on success, FALSE on failure
329
     */
330
    abstract protected function lock(string $id) : bool;
331

332
    /**
333
     * Unlock the current session lock id.
334
     *
335
     * @return bool Returns TRUE on success, FALSE on failure
336
     */
337
    abstract protected function unlock() : bool;
338
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc