Skip to content

Commit

Permalink
TypeRegistry registry constructor must check for duplicate instances
Browse files Browse the repository at this point in the history
  • Loading branch information
mvorisek committed Jul 13, 2023
1 parent d2b3a60 commit 71f1411
Showing 1 changed file with 8 additions and 20 deletions.
28 changes: 8 additions & 20 deletions src/Types/TypeRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@ final class TypeRegistry
{
/** @var array<string, Type> Map of type names and their corresponding flyweight objects. */
private array $instances;
/** @var array<int, string>|null */
private ?array $instancesReverseIndex = null;
/** @var array<int, string> */
private array $instancesReverseIndex;

/** @param array<string, Type> $instances */
public function __construct(array $instances = [])
{
$this->instances = [];
$this->instances = [];
$this->instancesReverseIndex = [];
foreach ($instances as $name => $type) {
$this->register($name, $type);
}
Expand Down Expand Up @@ -81,10 +82,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;
}

/**
Expand All @@ -102,10 +101,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;
}

/**
Expand All @@ -122,15 +119,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;
Expand Down

0 comments on commit 71f1411

Please sign in to comment.