1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Psi\Component\Grid; |
4
|
|
|
|
5
|
|
|
class Registry |
6
|
|
|
{ |
7
|
|
|
private $context; |
8
|
|
|
private $class; |
9
|
|
|
private $instances = []; |
10
|
|
|
private $aliases = []; |
11
|
|
|
|
12
|
|
|
public function __construct(string $class, string $context) |
13
|
|
|
{ |
14
|
|
|
$this->class = $class; |
15
|
|
|
$this->context = $context; |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
public function register($instance, $alias = null) |
19
|
|
|
{ |
20
|
|
|
if (!is_object($instance)) { |
21
|
|
|
throw new \InvalidArgumentException(sprintf( |
22
|
|
|
'Expected an object, but got an "%s".', |
23
|
|
|
gettype($instance) |
24
|
|
|
)); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
if (false === $instance instanceof $this->class) { |
28
|
|
|
throw new \InvalidArgumentException(sprintf( |
29
|
|
|
'Expected an instance of "%s", but got "%s"', |
30
|
|
|
$this->class, get_class($instance) |
31
|
|
|
)); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
$classFqn = get_class($instance); |
35
|
|
|
|
36
|
|
|
|
37
|
|
|
if (isset($this->instances[$classFqn])) { |
38
|
|
|
throw new \InvalidArgumentException(sprintf( |
39
|
|
|
'%s "%s" has already been registered', |
40
|
|
|
$this->context, $classFqn |
41
|
|
|
)); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
$this->instances[$classFqn] = $instance; |
45
|
|
|
|
46
|
|
|
if (null !== $alias) { |
47
|
|
|
if (isset($this->aliases[$alias])) { |
48
|
|
|
throw new \InvalidArgumentException(sprintf( |
49
|
|
|
'Alias "%s" has already been set to "%s"', |
50
|
|
|
$alias, $this->aliases[$alias] |
51
|
|
|
)); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
$this->aliases[$alias] = $classFqn; |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
public function get(string $classFqn) |
59
|
|
|
{ |
60
|
|
|
if (isset($this->aliases[$classFqn])) { |
61
|
|
|
$classFqn = $this->aliases[$classFqn]; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
if (!isset($this->instances[$classFqn])) { |
65
|
|
|
throw new \InvalidArgumentException(sprintf( |
66
|
|
|
'%s with name "%s" was not found. Known %s types: "%s", aliases: "%s"', |
67
|
|
|
$this->context, |
68
|
|
|
$classFqn, |
69
|
|
|
$this->context, |
70
|
|
|
implode('", "', array_keys($this->instances)), |
71
|
|
|
implode('", "', array_keys($this->aliases)) |
72
|
|
|
)); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
return $this->instances[$classFqn]; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
public function has(string $classFqn) |
79
|
|
|
{ |
80
|
|
|
return isset($this->instances[$classFqn]) || isset($this->aliases[$classFqn]); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|