Skip to content

Commit

Permalink
misc: use WeakMap to detect circular references
Browse files Browse the repository at this point in the history
  • Loading branch information
romm committed Oct 8, 2023
1 parent 6f59f02 commit e901ded
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions src/Normalizer/RecursiveNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
use stdClass;
use UnitEnum;

use WeakMap;

use function array_filter;
use function array_shift;
use function is_array;
Expand All @@ -31,22 +33,25 @@ public function __construct(private FunctionsContainer $handlers) {}

public function normalize(mixed $value): mixed
{
return $this->doNormalize($value, []);
/** @var WeakMap<object, true> $references */
$references = new WeakMap();

return $this->doNormalize($value, $references);
}

/**
* @param array<int, true> $references
* @param WeakMap<object, true> $references
*/
private function doNormalize(mixed $value, array $references): mixed
private function doNormalize(mixed $value, WeakMap $references): mixed
{
if (is_object($value)) {
$id = spl_object_id($value);

if (isset($references[$id])) {
if (isset($references[$value])) {
throw new CircularReferenceFoundDuringNormalization($value);
}

$references[$id] = true;
$references[$value] = true;

Check warning on line 54 in src/Normalizer/RecursiveNormalizer.php

View workflow job for this annotation

GitHub Actions / Mutation tests

Escaped Mutant for Mutator "TrueValue": --- Original +++ New @@ @@ if (isset($references[$value])) { throw new CircularReferenceFoundDuringNormalization($value); } - $references[$value] = true; + $references[$value] = false; } if ($this->handlers->count() === 0) { $value = $this->defaultNormalizer($value);
}

if ($this->handlers->count() === 0) {

Check warning on line 57 in src/Normalizer/RecursiveNormalizer.php

View workflow job for this annotation

GitHub Actions / Mutation tests

Escaped Mutant for Mutator "DecrementInteger": --- Original +++ New @@ @@ } $references[$value] = true; } - if ($this->handlers->count() === 0) { + if ($this->handlers->count() === -1) { $value = $this->defaultNormalizer($value); } else { $handlers = array_filter([...$this->handlers], fn(FunctionObject $function) => $function->definition()->parameters()->at(0)->type()->accepts($value));
Expand Down

0 comments on commit e901ded

Please sign in to comment.