Skip to content

Commit a278199

Browse files
committed
SimpleIdentity: reading an undeclared property throws (BC break)
Until now __get() returned null for an unknown key and, because it returns by reference, silently created that key in the data (and thus in the storage). It now throws MemberAccessException, like any other Nette object. This also ends the by-ref write pattern $identity->cart[] = $item on a key that has not been set yet.
1 parent effcf33 commit a278199

2 files changed

Lines changed: 19 additions & 2 deletions

File tree

src/Security/SimpleIdentity.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77

88
namespace Nette\Security;
99

10-
use function ctype_digit, in_array, is_string, iterator_to_array;
10+
use Nette;
11+
use function array_key_exists, ctype_digit, in_array, is_string, iterator_to_array;
1112

1213

1314
/**
@@ -112,8 +113,11 @@ public function &__get(string $key): mixed
112113
$res = $this->{'get' . ucfirst($key)}();
113114
return $res;
114115

115-
} else {
116+
} elseif (array_key_exists($key, $this->data)) {
116117
return $this->data[$key];
118+
119+
} else {
120+
Nette\Utils\ObjectHelpers::strictGet(static::class, $key);
117121
}
118122
}
119123

tests/Security/SimpleIdentity.phpt

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,16 @@ test('', function () {
3232
$id = new SimpleIdentity('12345678901234567890');
3333
Assert::same('12345678901234567890', $id->getId());
3434
});
35+
36+
37+
test('reading an undeclared data key throws and does not pollute data', function () {
38+
$id = new SimpleIdentity(12, 'admin', ['name' => 'John', 'note' => null]);
39+
Assert::null($id->note); // existing null value is readable
40+
41+
Assert::exception(
42+
fn() => $id->undeclared,
43+
Nette\MemberAccessException::class,
44+
'Cannot read an undeclared property Nette\Security\SimpleIdentity::$undeclared.',
45+
);
46+
Assert::same(['name' => 'John', 'note' => null], $id->getData());
47+
});

0 commit comments

Comments
 (0)