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

nette / component-model / 22884715739

04 Mar 2026 07:34AM UTC coverage: 87.444% (+0.3%) from 87.156%
22884715739

push

github

dg
made static analysis mandatory

195 of 223 relevant lines covered (87.44%)

0.87 hits per line

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

86.73
/src/ComponentModel/Container.php
1
<?php declare(strict_types=1);
1✔
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
namespace Nette\ComponentModel;
9

10
use Nette;
11
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, strval, ucfirst;
12

13

14
/**
15
 * Manages a collection of child components.
16
 *
17
 * @property-read IComponent[] $components
18
 */
19
class Container extends Component implements IContainer
20
{
21
        private const NameRegexp = '#^[a-zA-Z0-9_]+$#D';
22

23
        /** @var IComponent[] */
24
        private array $components = [];
25
        private ?Container $cloning = null;
26

27

28
        /********************* interface IContainer ****************d*g**/
29

30

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

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

48
                } elseif (isset($this->components[$name])) {
1✔
49
                        throw new Nette\InvalidStateException("Component with name '$name' already exists.");
×
50
                }
51

52
                // check circular reference
53
                $obj = $this;
1✔
54
                do {
55
                        if ($obj === $component) {
1✔
56
                                throw new Nette\InvalidStateException("Circular reference detected while adding component '$name'.");
×
57
                        }
58
                } while (($obj = $obj->getParent()) !== null);
1✔
59

60
                // user checking
61
                $this->validateChildComponent($component);
1✔
62

63
                if ($insertBefore !== null && isset($this->components[$insertBefore])) {
1✔
64
                        $tmp = [];
1✔
65
                        foreach ($this->components as $k => $v) {
1✔
66
                                if ((string) $k === $insertBefore) {
1✔
67
                                        $tmp[$name] = $component;
1✔
68
                                }
69

70
                                $tmp[$k] = $v;
1✔
71
                        }
72

73
                        $this->components = $tmp;
1✔
74
                } else {
75
                        $this->components[$name] = $component;
1✔
76
                }
77

78
                try {
79
                        $component->setParent($this, $name);
1✔
80
                } catch (\Throwable $e) {
1✔
81
                        unset($this->components[$name]); // undo
1✔
82
                        throw $e;
1✔
83
                }
84

85
                return $this;
1✔
86
        }
87

88

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

99
                unset($this->components[$name]);
1✔
100
                $component->setParent(null);
1✔
101
        }
1✔
102

103

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

113
                if (!isset($this->components[$name])) {
1✔
114
                        if (!preg_match(self::NameRegexp, $name)) {
1✔
115
                                return $throw
×
116
                                        ? throw new Nette\InvalidArgumentException("Component name must be non-empty alphanumeric string, '$name' given.")
×
117
                                        : null;
×
118
                        }
119

120
                        $component = $this->createComponent($name);
1✔
121
                        if ($component && !isset($this->components[$name])) {
1✔
122
                                $this->addComponent($component, $name);
1✔
123
                        }
124
                }
125

126
                $component = $this->components[$name] ?? null;
1✔
127
                if ($component !== null) {
1✔
128
                        if (!isset($parts[1])) {
1✔
129
                                return $component;
1✔
130

131
                        } elseif ($component instanceof IContainer) {
1✔
132
                                return $component->getComponent($parts[1], $throw);
1✔
133

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

145
                return null;
×
146
        }
147

148

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

167
                        return $component;
1✔
168
                }
169

170
                return null;
1✔
171
        }
172

173

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

190
                return $filterType
1✔
191
                        ? array_filter($this->components, fn($item) => $item instanceof $filterType)
1✔
192
                        : $this->components;
1✔
193
        }
194

195

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

212

213
        /**
214
         * Validates a child component before it's added to the container.
215
         * Descendant classes can override this to implement custom validation logic.
216
         * @throws Nette\InvalidStateException
217
         */
218
        protected function validateChildComponent(IComponent $child): void
1✔
219
        {
220
        }
1✔
221

222

223
        /********************* cloneable, serializable ****************d*g**/
224

225

226
        /**
227
         * Handles object cloning. Clones all child components and re-sets their parents.
228
         */
229
        public function __clone()
230
        {
231
                if ($this->components) {
1✔
232
                        $oldMyself = reset($this->components)->getParent();
1✔
233
                        assert($oldMyself instanceof self);
234
                        $oldMyself->cloning = $this;
1✔
235
                        foreach ($this->components as $name => $component) {
1✔
236
                                $this->components[$name] = clone $component;
1✔
237
                        }
238

239
                        $oldMyself->cloning = null;
1✔
240
                }
241

242
                parent::__clone();
1✔
243
        }
1✔
244

245

246
        /**
247
         * Is container cloning now?
248
         * @internal
249
         */
250
        final public function _isCloning(): ?self
251
        {
252
                return $this->cloning;
1✔
253
        }
254
}
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

© 2026 Coveralls, Inc