From 50296561eb1d0e9250f90282e36b96d1903a8e89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20Vo=C5=99=C3=AD=C5=A1ek?= Date: Sat, 1 Jul 2023 17:26:14 +0200 Subject: [PATCH] TypeRegistry registry constructor must check for duplicate instances --- src/Types/TypeRegistry.php | 32 ++++++++++++-------------------- tests/Types/TypeRegistryTest.php | 10 ++++++++++ 2 files changed, 22 insertions(+), 20 deletions(-) diff --git a/src/Types/TypeRegistry.php b/src/Types/TypeRegistry.php index ee9aba6386c..ff53dfe96f8 100644 --- a/src/Types/TypeRegistry.php +++ b/src/Types/TypeRegistry.php @@ -16,13 +16,18 @@ final class TypeRegistry { /** @var array Map of type names and their corresponding flyweight objects. */ private array $instances; - /** @var array|null */ - private ?array $instancesReverseIndex = null; + /** @var array */ + private array $instancesReverseIndex; /** @param array $instances */ public function __construct(array $instances = []) { - $this->instances = $instances; + $this->instances = []; + $this->instancesReverseIndex = []; + + foreach ($instances as $name => $type) { + $this->register($name, $type); + } } /** @@ -78,10 +83,8 @@ public function register(string $name, Type $type): void throw Exception::typeAlreadyRegistered($type); } - $this->instances[$name] = $type; - if ($this->instancesReverseIndex !== null) { - $this->instancesReverseIndex[spl_object_id($type)] = $name; - } + $this->instances[$name] = $type; + $this->instancesReverseIndex[spl_object_id($type)] = $name; } /** @@ -99,10 +102,8 @@ public function override(string $name, Type $type): void throw Exception::typeAlreadyRegistered($type); } - $this->instances[$name] = $type; - if ($this->instancesReverseIndex !== null) { - $this->instancesReverseIndex[spl_object_id($type)] = $name; - } + $this->instances[$name] = $type; + $this->instancesReverseIndex[spl_object_id($type)] = $name; } /** @@ -119,15 +120,6 @@ public function getMap(): array private function findTypeName(Type $type): ?string { - if ($this->instancesReverseIndex === null) { - $reverseIndex = []; - foreach ($this->instances as $name => $v) { - $reverseIndex[spl_object_id($v)] = $name; - } - - $this->instancesReverseIndex = $reverseIndex; - } - $name = $this->instancesReverseIndex[spl_object_id($type)] ?? null; if ($name !== null && $this->instances[$name] === $type) { return $name; diff --git a/tests/Types/TypeRegistryTest.php b/tests/Types/TypeRegistryTest.php index 42d57b69a56..0a5904252fe 100644 --- a/tests/Types/TypeRegistryTest.php +++ b/tests/Types/TypeRegistryTest.php @@ -99,6 +99,16 @@ public function testRegisterWithAlreadyRegisteredInstance(): void $this->registry->register('other', $newType); } + public function testConstructorWithDuplicateInstance(): void + { + $newType = new TextType(); + + new TypeRegistry(['a' => $newType]); + + $this->expectException(Exception::class); + new TypeRegistry(['a' => $newType, 'b' => $newType]); + } + public function testOverride(): void { $baseType = new TextType();