Skip to content

Commit

Permalink
Merge pull request #6 from TysonAndre/forbid-set
Browse files Browse the repository at this point in the history
Forbid serializing, setting dynamic property like native WeakMap
  • Loading branch information
BenMorel committed Jan 9, 2022
2 parents e98af44 + d85a514 commit 488ed36
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/WeakMap.php
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,18 @@ public function getIterator() : Traversable
$this->housekeepingCounter = 0;
}

// NOTE: The native WeakMap does not implement this method,
// but does throw Error for setting dynamic properties.
public function __set($name, $value): void {
throw new Error("Cannot create dynamic property WeakMap::\$$name");
}

// NOTE: The native WeakMap does not implement this method,
// but does forbid serialization.
public function __serialize(): void {
throw new Exception("Serialization of 'WeakMap' is not allowed");
}

private function housekeeping(bool $force = false) : void
{
if ($force || (++$this->housekeepingCounter >= self::HOUSEKEEPING_EVERY &&
Expand Down
16 changes: 16 additions & 0 deletions tests/WeakMapTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,22 @@ public function testCantDeepAppend() : void
$weakMap[][1] = 1;
}

public function testCantSetDynamicProperty() : void
{
$weakMap = new WeakMap();
self::expectException(Error::class);
self::expectExceptionMessage('Cannot create dynamic property WeakMap::$abc');
$weakMap->abc = 123;
}

public function testCantSerialize() : void
{
$weakMap = new WeakMap();
self::expectException(Exception::class);
self::expectExceptionMessage("Serialization of 'WeakMap' is not allowed");
serialize($weakMap);
}

/**
* Similar to iterator_to_array(), but returns the result as a list of key-value pairs.
* We need this, as iterator_to_array() on a WeakMap would fail because keys are objects.
Expand Down

0 comments on commit 488ed36

Please sign in to comment.