diff --git a/src/Mapper/Tree/Shell.php b/src/Mapper/Tree/Shell.php index 10831820..aa793494 100644 --- a/src/Mapper/Tree/Shell.php +++ b/src/Mapper/Tree/Shell.php @@ -11,7 +11,6 @@ use CuyZ\Valinor\Type\Type; use CuyZ\Valinor\Type\Types\UnresolvableType; -use function array_unshift; use function assert; use function implode; @@ -30,12 +29,16 @@ final class Shell private Attributes $attributes; - private self $parent; + /** @var list */ + private array $path; /** @var list */ private array $allowedSuperfluousKeys = []; - private function __construct(Settings $settings, Type $type) + /** + * @param list $path + */ + private function __construct(Settings $settings, Type $type, array $path = []) { if ($type instanceof UnresolvableType) { throw new UnresolvableShellType($type); @@ -43,6 +46,7 @@ private function __construct(Settings $settings, Type $type) $this->settings = $settings; $this->type = $type; + $this->path = $path; } public static function root( @@ -55,9 +59,10 @@ public static function root( public function child(string $name, Type $type, ?Attributes $attributes = null): self { - $instance = new self($this->settings, $type); + $path = $this->path; + $path[] = $name; + $instance = new self($this->settings, $type, $path); $instance->name = $name; - $instance->parent = $this; if ($attributes) { $instance->attributes = $attributes; @@ -73,7 +78,7 @@ public function name(): string public function isRoot(): bool { - return ! isset($this->parent); + return ! isset($this->name); } public function withType(Type $newType): self @@ -152,19 +157,11 @@ public function allowedSuperfluousKeys(): array public function path(): string { - if (! isset($this->parent)) { + if ($this->isRoot()) { return '*root*'; } - $node = $this; - $path = []; - - while (isset($node->parent)) { - array_unshift($path, $node->name); - $node = $node->parent; - } - - return implode('.', $path); + return implode('.', $this->path); } private static function castCompatibleValue(Type $type, mixed $value): mixed diff --git a/tests/Unit/Mapper/Tree/ShellTest.php b/tests/Unit/Mapper/Tree/ShellTest.php index a8b243c1..99e69f4c 100644 --- a/tests/Unit/Mapper/Tree/ShellTest.php +++ b/tests/Unit/Mapper/Tree/ShellTest.php @@ -80,6 +80,7 @@ public function test_shell_child_values_can_be_retrieved(): void $shell = Shell::root(new Settings(), new FakeType(), []); $child = $shell->child('foo', $type, $attributes)->withValue($value); + self::assertFalse($child->isRoot()); self::assertSame('foo', $child->name()); self::assertSame('foo', $child->path()); self::assertSame($type, $child->type());