-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathContainer.php
More file actions
245 lines (197 loc) · 6.38 KB
/
Container.php
File metadata and controls
245 lines (197 loc) · 6.38 KB
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\ComponentModel;
use Nette;
use function strval;
/**
* Manages a collection of child components.
*/
class Container extends Component implements IContainer
{
private const NameRegexp = '#^[a-zA-Z0-9_]+$#D';
/** @var IComponent[] */
private array $components = [];
private ?Container $cloning = null;
/********************* interface IContainer ****************d*g**/
/**
* Adds a child component to the container.
* @throws Nette\InvalidStateException
*/
public function addComponent(IComponent $component, ?string $name, ?string $insertBefore = null): static
{
if ($name === null) {
$name = $component->getName();
if ($name === null) {
throw new Nette\InvalidStateException("Missing component's name.");
}
}
if (!preg_match(self::NameRegexp, $name)) {
throw new Nette\InvalidArgumentException("Component name must be non-empty alphanumeric string, '$name' given.");
} elseif (isset($this->components[$name])) {
throw new Nette\InvalidStateException("Component with name '$name' already exists.");
}
// check circular reference
$obj = $this;
do {
if ($obj === $component) {
throw new Nette\InvalidStateException("Circular reference detected while adding component '$name'.");
}
} while (($obj = $obj->getParent()) !== null);
// user checking
$this->validateChildComponent($component);
if ($insertBefore !== null && isset($this->components[$insertBefore])) {
$tmp = [];
foreach ($this->components as $k => $v) {
if ((string) $k === $insertBefore) {
$tmp[$name] = $component;
}
$tmp[$k] = $v;
}
$this->components = $tmp;
} else {
$this->components[$name] = $component;
}
try {
$component->setParent($this, $name);
} catch (\Throwable $e) {
unset($this->components[$name]); // undo
throw $e;
}
return $this;
}
/**
* Removes a child component from the container.
*/
public function removeComponent(IComponent $component): void
{
$name = $component->getName();
if ($name === null || ($this->components[$name] ?? null) !== $component) {
throw new Nette\InvalidArgumentException("Component named '$name' is not located in this container.");
}
unset($this->components[$name]);
$component->setParent(null);
}
/**
* Retrieves a child component by name or creates it if it doesn't exist.
* @param bool $throw throw exception if component doesn't exist?
* @return ($throw is true ? IComponent : ?IComponent)
*/
final public function getComponent(string $name, bool $throw = true): ?IComponent
{
[$name] = $parts = explode(self::NameSeparator, $name, 2);
if (!isset($this->components[$name])) {
if (!preg_match(self::NameRegexp, $name)) {
return $throw
? throw new Nette\InvalidArgumentException("Component name must be non-empty alphanumeric string, '$name' given.")
: null;
}
$component = $this->createComponent($name);
if ($component && !isset($this->components[$name])) {
$this->addComponent($component, $name);
}
}
$component = $this->components[$name] ?? null;
if ($component !== null) {
if (!isset($parts[1])) {
return $component;
} elseif ($component instanceof IContainer) {
return $component->getComponent($parts[1], $throw);
} elseif ($throw) {
throw new Nette\InvalidArgumentException("Component with name '$name' is not container and cannot have '$parts[1]' component.");
}
} elseif ($throw) {
$hint = Nette\Utils\ObjectHelpers::getSuggestion(array_merge(
array_map(strval(...), array_keys($this->components)),
array_map(lcfirst(...), preg_filter('#^createComponent([A-Z0-9].*)#', '$1', get_class_methods($this))),
), $name);
throw new Nette\InvalidArgumentException("Component with name '$name' does not exist" . ($hint ? ", did you mean '$hint'?" : '.'));
}
return null;
}
/**
* Creates a new component. Delegates creation to createComponent<Name> method if it exists.
*/
protected function createComponent(string $name): ?IComponent
{
$ucname = ucfirst($name);
$method = 'createComponent' . $ucname;
if (
$ucname !== $name
&& method_exists($this, $method)
&& (new \ReflectionMethod($this, $method))->getName() === $method
) {
$component = $this->$method($name);
if (!$component instanceof IComponent && !isset($this->components[$name])) {
$class = static::class;
throw new Nette\UnexpectedValueException("Method $class::$method() did not return or create the desired component.");
}
return $component;
}
return null;
}
/**
* Returns all immediate child components.
* @return IComponent[]
*/
final public function getComponents(): array
{
if (func_get_args()[0] ?? null) {
throw new Nette\DeprecatedException(__METHOD__ . '() with recursive flag is deprecated. Use getComponentTree() instead.');
}
if (func_get_args()[1] ?? null) {
throw new Nette\DeprecatedException('Using Container::getComponents() with filter type is deprecated.');
}
return $this->components;
}
/**
* Retrieves the entire hierarchy of components, including all nested child components (depth-first).
* @return list<IComponent>
*/
final public function getComponentTree(): array
{
$res = [];
foreach ($this->components as $component) {
$res[] = $component;
if ($component instanceof self) {
$res = array_merge($res, $component->getComponentTree());
}
}
return $res;
}
/**
* Validates a child component before it's added to the container.
* Descendant classes can override this to implement custom validation logic.
* @throws Nette\InvalidStateException
*/
protected function validateChildComponent(IComponent $child): void
{
}
/********************* cloneable, serializable ****************d*g**/
/**
* Handles object cloning. Clones all child components and re-sets their parents.
*/
public function __clone()
{
if ($this->components) {
$oldMyself = reset($this->components)->getParent();
assert($oldMyself instanceof self);
$oldMyself->cloning = $this;
foreach ($this->components as $name => $component) {
$this->components[$name] = clone $component;
}
$oldMyself->cloning = null;
}
parent::__clone();
}
/**
* Is container cloning now?
* @internal
*/
final public function _isCloning(): ?self
{
return $this->cloning;
}
}