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

nette / component-model / 15762957805

19 Jun 2025 05:00PM UTC coverage: 85.514%. Remained the same
15762957805

push

github

dg
removed attached() & detached() methods (BC break)

1 of 2 new or added lines in 1 file covered. (50.0%)

25 existing lines in 4 files now uncovered.

183 of 214 relevant lines covered (85.51%)

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
 * @property-read T[] $components
22
 */
23
class Container extends Component implements IContainer
24
{
25
        private const NameRegexp = '#^[a-zA-Z0-9_]+$#D';
26

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

31

32
        /********************* interface IContainer ****************d*g**/
33

34

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

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

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

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

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

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

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

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

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

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

91
                return $this;
1✔
92
        }
93

94

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

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

109

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

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

UNCOV
125
                                return null;
×
126
                        }
127

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

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

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

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

UNCOV
153
                return null;
×
154
        }
155

156

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

175
                        return $component;
1✔
176
                }
177

178
                return null;
1✔
179
        }
180

181

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

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

203

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

220

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

230

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

233

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

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

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

253

254
        /**
255
         * Is container cloning now?
256
         * @internal
257
         */
258
        final public function _isCloning(): ?self
259
        {
260
                return $this->cloning;
1✔
261
        }
262
}
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