• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nette / component-model / 19783748036

29 Nov 2025 12:16PM UTC coverage: 85.981%. Remained the same
19783748036

push

github

dg
Container::addComponent() added typehint

1 of 1 new or added line in 1 file covered. (100.0%)

9 existing lines in 1 file now uncovered.

184 of 214 relevant lines covered (85.98%)

0.86 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

86.73
/src/ComponentModel/Container.php
1
<?php
2

3
/**
4
 * This file is part of the Nette Framework (https://nette.org)
5
 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6
 */
7

8
declare(strict_types=1);
9

10
namespace Nette\ComponentModel;
11

12
use Nette;
13
use function array_filter, array_keys, array_map, array_merge, assert, explode, func_get_args, get_class_methods, method_exists, preg_filter, preg_match, reset, ucfirst;
14

15

16
/**
17
 * Manages a collection of child components.
18
 *
19
 * @template T of IComponent
20
 * @implements IContainer<T>
21
 */
22
class Container extends Component implements IContainer
23
{
24
        private const NameRegexp = '#^[a-zA-Z0-9_]+$#D';
25

26
        /** @var IComponent[] */
27
        private array $components = [];
28
        private ?Container $cloning = null;
29

30

31
        /********************* interface IContainer ****************d*g**/
32

33

34
        /**
35
         * Adds a child component to the container.
36
         * @throws Nette\InvalidStateException
37
         */
38
        public function addComponent(IComponent $component, ?string $name, ?string $insertBefore = null): static
1✔
39
        {
40
                if ($name === null) {
1✔
41
                        $name = $component->getName();
×
42
                        if ($name === null) {
×
UNCOV
43
                                throw new Nette\InvalidStateException("Missing component's name.");
×
44
                        }
45
                }
46

47
                if (!preg_match(self::NameRegexp, $name)) {
1✔
UNCOV
48
                        throw new Nette\InvalidArgumentException("Component name must be non-empty alphanumeric string, '$name' given.");
×
49
                }
50

51
                if (isset($this->components[$name])) {
1✔
UNCOV
52
                        throw new Nette\InvalidStateException("Component with name '$name' already exists.");
×
53
                }
54

55
                // check circular reference
56
                $obj = $this;
1✔
57
                do {
58
                        if ($obj === $component) {
1✔
UNCOV
59
                                throw new Nette\InvalidStateException("Circular reference detected while adding component '$name'.");
×
60
                        }
61

62
                        $obj = $obj->getParent();
1✔
63
                } while ($obj !== null);
1✔
64

65
                // user checking
66
                $this->validateChildComponent($component);
1✔
67

68
                if ($insertBefore !== null && isset($this->components[$insertBefore])) {
1✔
69
                        $tmp = [];
1✔
70
                        foreach ($this->components as $k => $v) {
1✔
71
                                if ((string) $k === $insertBefore) {
1✔
72
                                        $tmp[$name] = $component;
1✔
73
                                }
74

75
                                $tmp[$k] = $v;
1✔
76
                        }
77

78
                        $this->components = $tmp;
1✔
79
                } else {
80
                        $this->components[$name] = $component;
1✔
81
                }
82

83
                try {
84
                        $component->setParent($this, $name);
1✔
85
                } catch (\Throwable $e) {
1✔
86
                        unset($this->components[$name]); // undo
1✔
87
                        throw $e;
1✔
88
                }
89

90
                return $this;
1✔
91
        }
92

93

94
        /**
95
         * Removes a child component from the container.
96
         */
97
        public function removeComponent(IComponent $component): void
1✔
98
        {
99
                $name = $component->getName();
1✔
100
                if (($this->components[$name] ?? null) !== $component) {
1✔
UNCOV
101
                        throw new Nette\InvalidArgumentException("Component named '$name' is not located in this container.");
×
102
                }
103

104
                unset($this->components[$name]);
1✔
105
                $component->setParent(null);
1✔
106
        }
1✔
107

108

109
        /**
110
         * Retrieves a child component by name or creates it if it doesn't exist.
111
         * @param  bool  $throw  throw exception if component doesn't exist?
112
         * @return ($throw is true ? IComponent : ?IComponent)
113
         */
114
        final public function getComponent(string $name, bool $throw = true): ?IComponent
1✔
115
        {
116
                [$name] = $parts = explode(self::NameSeparator, $name, 2);
1✔
117

118
                if (!isset($this->components[$name])) {
1✔
119
                        if (!preg_match(self::NameRegexp, $name)) {
1✔
120
                                if ($throw) {
×
UNCOV
121
                                        throw new Nette\InvalidArgumentException("Component name must be non-empty alphanumeric string, '$name' given.");
×
122
                                }
123

UNCOV
124
                                return null;
×
125
                        }
126

127
                        $component = $this->createComponent($name);
1✔
128
                        if ($component && !isset($this->components[$name])) {
1✔
129
                                $this->addComponent($component, $name);
1✔
130
                        }
131
                }
132

133
                $component = $this->components[$name] ?? null;
1✔
134
                if ($component !== null) {
1✔
135
                        if (!isset($parts[1])) {
1✔
136
                                return $component;
1✔
137

138
                        } elseif ($component instanceof IContainer) {
1✔
139
                                return $component->getComponent($parts[1], $throw);
1✔
140

141
                        } elseif ($throw) {
×
UNCOV
142
                                throw new Nette\InvalidArgumentException("Component with name '$name' is not container and cannot have '$parts[1]' component.");
×
143
                        }
144
                } elseif ($throw) {
1✔
145
                        $hint = Nette\Utils\ObjectHelpers::getSuggestion(array_merge(
1✔
146
                                array_map('strval', array_keys($this->components)),
1✔
147
                                array_map('lcfirst', preg_filter('#^createComponent([A-Z0-9].*)#', '$1', get_class_methods($this))),
1✔
148
                        ), $name);
149
                        throw new Nette\InvalidArgumentException("Component with name '$name' does not exist" . ($hint ? ", did you mean '$hint'?" : '.'));
1✔
150
                }
151

UNCOV
152
                return null;
×
153
        }
154

155

156
        /**
157
         * Creates a new component. Delegates creation to createComponent<Name> method if it exists.
158
         */
159
        protected function createComponent(string $name): ?IComponent
1✔
160
        {
161
                $ucname = ucfirst($name);
1✔
162
                $method = 'createComponent' . $ucname;
1✔
163
                if (
164
                        $ucname !== $name
1✔
165
                        && method_exists($this, $method)
1✔
166
                        && (new \ReflectionMethod($this, $method))->getName() === $method
1✔
167
                ) {
168
                        $component = $this->$method($name);
1✔
169
                        if (!$component instanceof IComponent && !isset($this->components[$name])) {
1✔
170
                                $class = static::class;
1✔
171
                                throw new Nette\UnexpectedValueException("Method $class::$method() did not return or create the desired component.");
1✔
172
                        }
173

174
                        return $component;
1✔
175
                }
176

177
                return null;
1✔
178
        }
179

180

181
        /**
182
         * Returns all immediate child components.
183
         * @return array<int|string,IComponent>
184
         */
185
        final public function getComponents(): iterable
186
        {
187
                $filterType = func_get_args()[1] ?? null;
1✔
188
                if (func_get_args()[0] ?? null) { // back compatibility
1✔
189
                        $iterator = new RecursiveComponentIterator($this->components);
1✔
190
                        $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST);
1✔
191
                        if ($filterType) {
1✔
192
                                $iterator = new \CallbackFilterIterator($iterator, fn($item) => $item instanceof $filterType);
1✔
193
                        }
194
                        return $iterator;
1✔
195
                }
196

197
                return $filterType
1✔
198
                        ? array_filter($this->components, fn($item) => $item instanceof $filterType)
1✔
199
                        : $this->components;
1✔
200
        }
201

202

203
        /**
204
         * Retrieves the entire hierarchy of components, including all nested child components (depth-first).
205
         * @return list<IComponent>
206
         */
207
        final public function getComponentTree(): array
208
        {
209
                $res = [];
1✔
210
                foreach ($this->components as $component) {
1✔
211
                        $res[] = $component;
1✔
212
                        if ($component instanceof self) {
1✔
213
                                $res = array_merge($res, $component->getComponentTree());
1✔
214
                        }
215
                }
216
                return $res;
1✔
217
        }
218

219

220
        /**
221
         * Validates a child component before it's added to the container.
222
         * Descendant classes can override this to implement custom validation logic.
223
         * @throws Nette\InvalidStateException
224
         */
225
        protected function validateChildComponent(IComponent $child): void
1✔
226
        {
227
        }
1✔
228

229

230
        /********************* cloneable, serializable ****************d*g**/
231

232

233
        /**
234
         * Handles object cloning. Clones all child components and re-sets their parents.
235
         */
236
        public function __clone()
237
        {
238
                if ($this->components) {
1✔
239
                        $oldMyself = reset($this->components)->getParent();
1✔
240
                        assert($oldMyself instanceof self);
241
                        $oldMyself->cloning = $this;
1✔
242
                        foreach ($this->components as $name => $component) {
1✔
243
                                $this->components[$name] = clone $component;
1✔
244
                        }
245

246
                        $oldMyself->cloning = null;
1✔
247
                }
248

249
                parent::__clone();
1✔
250
        }
1✔
251

252

253
        /**
254
         * Is container cloning now?
255
         * @internal
256
         */
257
        final public function _isCloning(): ?self
258
        {
259
                return $this->cloning;
1✔
260
        }
261
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc