|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the Koded package. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Mihail Binev <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* Please view the LICENSE distributed with this source code |
|
9
|
|
|
* for the full copyright and license information. |
|
10
|
|
|
* |
|
11
|
|
|
*/ |
|
12
|
|
|
|
|
13
|
|
|
namespace Koded\Session; |
|
14
|
|
|
|
|
15
|
|
|
use Koded\Stdlib\Interfaces\ConfigurationFactory; |
|
16
|
|
|
use SessionHandlerInterface; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* Creates the Session object if not already instantiated, |
|
20
|
|
|
* or returns an instance of Session. |
|
21
|
|
|
* |
|
22
|
|
|
* @param Session $instance [optional] |
|
23
|
|
|
* |
|
24
|
|
|
* @return Session |
|
25
|
|
|
*/ |
|
26
|
|
|
function session(Session $instance = null): Session |
|
27
|
|
|
{ |
|
28
|
64 |
|
static $session; |
|
29
|
|
|
|
|
30
|
64 |
|
if ($instance) { |
|
31
|
64 |
|
return $session = $instance; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
1 |
|
return $session ?? $session = new PhpSession; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* Creates and registers a new session handler. |
|
39
|
|
|
* |
|
40
|
|
|
* @param ConfigurationFactory $configuration |
|
41
|
|
|
* |
|
42
|
|
|
* @return SessionConfiguration The session configuration instance |
|
43
|
|
|
* @throws SessionException |
|
44
|
|
|
*/ |
|
45
|
|
|
function session_register_custom_handler(ConfigurationFactory $configuration): SessionConfiguration |
|
46
|
|
|
{ |
|
47
|
66 |
|
$configuration = new SessionConfiguration($configuration); |
|
48
|
|
|
|
|
49
|
66 |
|
if (PHP_SESSION_ACTIVE !== session_status()) { |
|
50
|
66 |
|
session_set_save_handler(session_create_custom_handler($configuration), false); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
66 |
|
return $configuration; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* Factory for creating a session handler. |
|
58
|
|
|
* |
|
59
|
|
|
* @param SessionConfiguration $configuration |
|
60
|
|
|
* |
|
61
|
|
|
* @return SessionHandlerInterface |
|
62
|
|
|
*/ |
|
63
|
|
|
function session_create_custom_handler(SessionConfiguration $configuration): SessionHandlerInterface |
|
64
|
|
|
{ |
|
65
|
67 |
|
$handler = __NAMESPACE__ . '\\Handler\\' . ucfirst($configuration->handler()) . 'Handler'; |
|
66
|
|
|
|
|
67
|
67 |
|
if (false === class_exists($handler, true)) { |
|
68
|
1 |
|
throw SessionException::forNotFoundHandler($handler); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
66 |
|
return new $handler($configuration); |
|
72
|
|
|
} |
|
73
|
|
|
|