forked from jasny/session-middleware
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGlobalSession.php
More file actions
138 lines (114 loc) · 2.67 KB
/
Copy pathGlobalSession.php
File metadata and controls
138 lines (114 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
<?php
declare(strict_types=1);
namespace Jasny\Session;
use Jasny\Session\Flash\FlashBag;
use Jasny\Session\Flash\FlashTrait;
/**
* Wrapper round $_SESSION.
*/
class GlobalSession implements SessionInterface
{
use FlashTrait;
/** @var array<string,mixed> */
protected array $options;
/**
* Session constructor.
*
* @param array<string,mixed> $options Passed to session_start()
* @param FlashBag|null $flashBag
*/
public function __construct(array $options = [], ?FlashBag $flashBag = null)
{
$this->options = $options;
$this->flashBag = $flashBag ?? new FlashBag();
}
/**
* Start the session.
* @see session_start()
*/
public function start(): void
{
session_start($this->options);
}
/**
* Write session data and end session.
* @see session_write_close()
*/
public function stop(): void
{
session_write_close();
}
/**
* Discard session array changes and finish session.
* @see session_abort()
*
* Only a shallow clone is done to save the original data. If the session data contains objects, make sure that
* `__clone()` is overwritten, so it does a deep clone.
*/
public function abort(): void
{
session_abort();
}
/**
* Get the sessions status.
* @see session_status()
*/
public function status(): int
{
return session_status();
}
/**
* Clear all data from the session.
*/
public function clear(): void
{
$this->assertStarted();
$_SESSION = [];
}
/**
* @param string $offset
* @return bool
*/
public function offsetExists($offset): bool
{
$this->assertStarted();
return array_key_exists($offset, $_SESSION);
}
/**
* @param string $offset
* @return mixed
*/
public function offsetGet($offset)
{
$this->assertStarted();
return $_SESSION[$offset];
}
/**
* @param string $offset
* @param mixed $value
*/
public function offsetSet($offset, $value): void
{
$this->assertStarted();
$_SESSION[$offset] = $value;
}
/**
* @param string $offset
*/
public function offsetUnset($offset): void
{
$this->assertStarted();
unset($_SESSION[$offset]);
}
/**
* Assert that there is an active session.
*
* @throws \RuntimeException
*/
protected function assertStarted(): void
{
if (session_status() !== \PHP_SESSION_ACTIVE) {
throw new \RuntimeException("Session not started");
}
}
}