-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathTypeRegistry.php
125 lines (103 loc) · 2.77 KB
/
TypeRegistry.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
<?php
declare(strict_types=1);
namespace Doctrine\DBAL\Types;
use Doctrine\DBAL\Exception;
use function array_search;
use function in_array;
/**
* The type registry is responsible for holding a map of all known DBAL types.
* The types are stored using the flyweight pattern so that one type only exists as exactly one instance.
*/
final class TypeRegistry
{
/** @var array<string, Type> Map of type names and their corresponding flyweight objects. */
private $instances;
/**
* @param array<string, Type> $instances
*/
public function __construct(array $instances = [])
{
$this->instances = $instances;
}
/**
* Finds a type by the given name.
*
* @throws Exception
*/
public function get(string $name): Type
{
if (! isset($this->instances[$name])) {
throw Exception::unknownColumnType($name);
}
return $this->instances[$name];
}
/**
* Finds a name for the given type.
*
* @throws Exception
*/
public function lookupName(Type $type): string
{
$name = $this->findTypeName($type);
if ($name === null) {
throw Exception::typeNotRegistered($type);
}
return $name;
}
/**
* Checks if there is a type of the given name.
*/
public function has(string $name): bool
{
return isset($this->instances[$name]);
}
/**
* Registers a custom type to the type map.
*
* @throws Exception
*/
public function register(string $name, Type $type): void
{
if (isset($this->instances[$name])) {
throw Exception::typeExists($name);
}
if ($this->findTypeName($type) !== null) {
throw Exception::typeAlreadyRegistered($type);
}
$this->instances[$name] = $type;
}
/**
* Overrides an already defined type to use a different implementation.
*
* @throws Exception
*/
public function override(string $name, Type $type): void
{
if (! isset($this->instances[$name])) {
throw Exception::typeNotFound($name);
}
if (! in_array($this->findTypeName($type), [$name, null], true)) {
throw Exception::typeAlreadyRegistered($type);
}
$this->instances[$name] = $type;
}
/**
* Gets the map of all registered types and their corresponding type instances.
*
* @internal
*
* @return array<string, Type>
*/
public function getMap(): array
{
return $this->instances;
}
private function findTypeName(Type $type): ?string
{
$name = array_search($type, $this->instances, true);
if ($name === false) {
return null;
}
return $name;
}
}