Skip to content

Commit e400fa1

Browse files
committed
Add __set that throws to fully enforce Location immutability
Without __set, PHP 8.2+ only emits a deprecation for dynamic property assignment rather than preventing it. Adding an explicit __set that throws BadMethodCallException closes this gap.
1 parent ae93c93 commit e400fa1

2 files changed

Lines changed: 20 additions & 0 deletions

File tree

src/Location.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,16 @@ public function offsetUnset(mixed $offset): void
185185
throw new \BadMethodCallException('Location is immutable.');
186186
}
187187

188+
/**
189+
* Prevent setting properties directly.
190+
*
191+
* @throws \BadMethodCallException Always, as Location is immutable.
192+
*/
193+
public function __set(string $key, mixed $value): void
194+
{
195+
throw new \BadMethodCallException('Location is immutable. Use withAttribute() instead.');
196+
}
197+
188198
/** Check if the location's attribute is set */
189199
public function __isset($key): bool
190200
{

tests/LocationTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,16 @@ public function with_attribute_returns_new_instance_and_original_is_unchanged():
2727
$this->assertSame('81.2.69.142', $modified->ip);
2828
}
2929

30+
#[Test]
31+
public function setting_property_via_magic_set_throws_bad_method_call_exception(): void
32+
{
33+
$location = new Location(['ip' => '127.0.0.1']);
34+
35+
$this->expectException(\BadMethodCallException::class);
36+
37+
$location->ip = '10.0.0.1';
38+
}
39+
3040
#[Test]
3141
public function offset_set_throws_bad_method_call_exception(): void
3242
{

0 commit comments

Comments
 (0)