Skip to content

Commit 75ce8a0

Browse files
author
Yani
committed
add ArrayAccess to Session class + throw error on invalid property retrieval
1 parent 19358d0 commit 75ce8a0

File tree

1 file changed

+65
-2
lines changed

1 file changed

+65
-2
lines changed

src/Session.php

Lines changed: 65 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55
namespace Compwright\PhpSession;
66

77
use Countable;
8+
use ArrayAccess;
89
use RuntimeException;
910

10-
class Session implements Countable
11+
class Session implements ArrayAccess, Countable
1112
{
1213
protected string $name;
1314

@@ -50,7 +51,12 @@ public function __get(string $name)
5051
throw new RuntimeException('Session not initialized');
5152
}
5253

53-
return $this->contents[$name] ?? null;
54+
if (!isset($this->contents[$name])) {
55+
\trigger_error('Undefined property: ' . self::class . '::$' . $name, \E_USER_WARNING);
56+
return null;
57+
}
58+
59+
return $this->contents[$name];
5460
}
5561

5662
public function __isset(string $name): bool
@@ -89,10 +95,67 @@ public function __unset(string $name): void
8995
throw new RuntimeException('Cannot alter session after it is closed');
9096
}
9197

98+
if (!isset($this->contents[$name])) {
99+
\trigger_error('Undefined property: ' . self::class . '::$' . $name, \E_USER_WARNING);
100+
return;
101+
}
102+
92103
$this->modified = true;
93104
unset($this->contents[$name]);
94105
}
95106

107+
public function offsetSet($name, $value): void
108+
{
109+
if (!$this->isInitialized()) {
110+
throw new RuntimeException('Session not initialized');
111+
}
112+
113+
if (!$this->writeable) {
114+
throw new RuntimeException('Cannot alter session after it is closed');
115+
}
116+
117+
$this->modified = true;
118+
$this->contents[$name] = $value;
119+
}
120+
121+
public function offsetExists($name): bool
122+
{
123+
if (!$this->isInitialized()) {
124+
throw new RuntimeException('Session not initialized');
125+
}
126+
127+
return isset($this->contents[$name]);
128+
}
129+
130+
public function offsetUnset($name): void
131+
{
132+
if (!$this->isInitialized()) {
133+
throw new RuntimeException('Session not initialized');
134+
}
135+
136+
if (!$this->writeable) {
137+
throw new RuntimeException('Cannot alter session after it is closed');
138+
}
139+
140+
if (!isset($this->contents[$name])) {
141+
\trigger_error('Undefined array key "' . $name . '"', \E_USER_WARNING);
142+
return;
143+
}
144+
145+
$this->modified = true;
146+
unset($this->contents[$name]);
147+
}
148+
149+
public function offsetGet($name): mixed
150+
{
151+
if (!isset($this->contents[$name])) {
152+
\trigger_error('Undefined array key "' . $name . '"', \E_USER_WARNING);
153+
return null;
154+
}
155+
156+
return $this->contents[$name];
157+
}
158+
96159
/**
97160
* @param ?array<string, mixed> $contents
98161
*/

0 commit comments

Comments
 (0)