Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
15 / 15 |
|
100.00% |
5 / 5 |
CRAP | |
100.00% |
1 / 1 |
Session | |
100.00% |
15 / 15 |
|
100.00% |
5 / 5 |
9 | |
100.00% |
1 / 1 |
get | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
set | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
begin | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 | |||
commit | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 | |||
getSessionId | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
3 |
1 | <?php |
2 | |
3 | namespace Miniframe\Middleware; |
4 | |
5 | use Miniframe\Core\AbstractMiddleware; |
6 | |
7 | class Session extends AbstractMiddleware |
8 | { |
9 | /** |
10 | * True when a session is active |
11 | * |
12 | * @var bool |
13 | */ |
14 | private $sessionStarted = false; |
15 | |
16 | /** |
17 | * Gets a session value |
18 | * |
19 | * @param string $key Name of the session item. |
20 | * |
21 | * @return mixed |
22 | */ |
23 | public function get(string $key) |
24 | { |
25 | $this->begin(); |
26 | return $_SESSION[$key] ?? null; |
27 | } |
28 | |
29 | /** |
30 | * Sets a session value |
31 | * |
32 | * @param string $key Name of the session item. |
33 | * @param mixed $value Value to put in the session. |
34 | * |
35 | * @return void |
36 | */ |
37 | public function set(string $key, $value): void |
38 | { |
39 | $this->begin(); |
40 | $_SESSION[$key] = $value; |
41 | } |
42 | |
43 | /** |
44 | * Starts the PHP session handler |
45 | * |
46 | * @return void |
47 | */ |
48 | public function begin(): void |
49 | { |
50 | if ($this->sessionStarted === true) { |
51 | return; |
52 | } |
53 | session_start(); |
54 | $this->sessionStarted = true; |
55 | } |
56 | |
57 | /** |
58 | * Commit changes to the session handler and releases the connection to prevent processes to wait for each other |
59 | * |
60 | * @return void |
61 | */ |
62 | public function commit(): void |
63 | { |
64 | if ($this->sessionStarted === false) { |
65 | return; |
66 | } |
67 | session_write_close(); |
68 | $this->sessionStarted = false; |
69 | } |
70 | |
71 | /** |
72 | * Returns the current session ID, or null when there's no active session |
73 | * |
74 | * @return string|null |
75 | */ |
76 | public function getSessionId(): ?string |
77 | { |
78 | if ($this->sessionStarted) { |
79 | return session_id() ?: null; |
80 | } |
81 | return null; |
82 | } |
83 | } |