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

nette / component-model / 21199912604

21 Jan 2026 06:40AM UTC coverage: 86.7% (+0.3%) from 86.408%
21199912604

push

github

dg
Component: attached handles are called top-down (ancestor → descendant) (BC break)

Implementation handles tree mutations during listener execution:
- Listeners can modify tree (remove self, siblings, parent)
- Validity check before processing children
- Deduplication prevents calling same listener twice
- Reentry guard prevents infinite loops

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

11 existing lines in 1 file now uncovered.

176 of 203 relevant lines covered (86.7%)

0.87 hits per line

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

88.46
/src/ComponentModel/Component.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 in_array, substr;
14

15

16
/**
17
 * Base class for all components. Components have a parent, name, and can be monitored by ancestors.
18
 */
19
abstract class Component implements IComponent
20
{
21
        use Nette\SmartObject;
22

23
        private ?IContainer $parent = null;
24
        private ?string $name = null;
25

26
        /**
27
         * Monitors: tracks monitored ancestors and registered callbacks.
28
         * Combines cached lookup results with callback registrations for each monitored type.
29
         * Depth is used to detect when monitored ancestor becomes unreachable during detachment.
30
         * Structure: [type => [found object, depth to object, path to object, [[attached, detached], ...]]]
31
         * @var array<''|class-string<Nette\ComponentModel\IComponent>, array{?IComponent, ?int, ?string, array<int, array{?\Closure, ?\Closure}>}>
32
         */
33
        private array $monitors = [];
34

35

36
        /**
37
         * Finds the closest ancestor of specified type.
38
         * @template T of IComponent
39
         * @param ?class-string<T>  $type
40
         * @param bool  $throw  throw exception if component doesn't exist?
41
         * @return ($type is null ? ($throw is true ? IComponent : ?IComponent) : ($throw is true ? T : ?T))
42
         */
43
        final public function lookup(?string $type, bool $throw = true): ?IComponent
1✔
44
        {
45
                $type ??= '';
1✔
46
                if (!isset($this->monitors[$type])) { // not monitored or not processed yet
1✔
47
                        $ancestor = $this->parent;
1✔
48
                        $path = self::NameSeparator . $this->name;
1✔
49
                        $depth = 1;
1✔
50
                        while ($ancestor !== null) {
1✔
51
                                $parent = $ancestor->getParent();
1✔
52
                                if ($type ? $ancestor instanceof $type : $parent === null) {
1✔
53
                                        break;
1✔
54
                                }
55

56
                                $path = self::NameSeparator . $ancestor->getName() . $path;
1✔
57
                                $depth++;
1✔
58
                                $ancestor = $parent; // IComponent::getParent()
1✔
59
                                if ($ancestor === $this) {
1✔
UNCOV
60
                                        $ancestor = null; // prevent cycling
×
61
                                }
62
                        }
63

64
                        $this->monitors[$type] = $ancestor
1✔
65
                                ? [$ancestor, $depth, substr($path, 1), []]
1✔
66
                                : [null, null, null, []]; // not found
1✔
67
                }
68

69
                if ($throw && $this->monitors[$type][0] === null) {
1✔
70
                        $desc = $this->name === null ? "type of '" . static::class . "'" : "'$this->name'";
1✔
71
                        throw new Nette\InvalidStateException("Component $desc is not attached to '$type'.");
1✔
72
                }
73

74
                return $this->monitors[$type][0];
1✔
75
        }
76

77

78
        /**
79
         * Finds the closest ancestor specified by class or interface name and returns backtrace path.
80
         * A path is the concatenation of component names separated by self::NameSeparator.
81
         * @param ?class-string<IComponent>  $type
82
         * @param bool  $throw  throw exception if component doesn't exist?
83
         * @return ($throw is true ? string : ?string)
84
         */
85
        final public function lookupPath(?string $type = null, bool $throw = true): ?string
1✔
86
        {
87
                $this->lookup($type, $throw);
1✔
88
                return $this->monitors[$type ?? ''][2];
1✔
89
        }
90

91

92
        /**
93
         * Starts monitoring ancestors for attach/detach events.
94
         * @template T of IComponent
95
         * @param class-string<T>  $type
96
         * @param ?(callable(T): void)  $attached  called when attached to a monitored ancestor
97
         * @param ?(callable(T): void)  $detached  called before detaching from a monitored ancestor
98
         */
99
        final public function monitor(string $type, ?callable $attached = null, ?callable $detached = null): void
1✔
100
        {
101
                if (!$attached && !$detached) {
1✔
UNCOV
102
                        throw new Nette\InvalidStateException('At least one handler is required.');
×
103
                }
104
                $attached = $attached ? $attached(...) : null;
1✔
105
                $detached = $detached ? $detached(...) : null;
1✔
106

107
                if (
108
                        $attached
1✔
109
                        && ($ancestor = $this->lookup($type, throw: false))
1✔
110
                        && !in_array([$attached, $detached], $this->monitors[$type][3], strict: false)
1✔
111
                ) {
112
                        $attached($ancestor);
1✔
113
                }
114

115
                $this->monitors[$type][3][] = [$attached, $detached]; // mark as monitored
1✔
116
        }
1✔
117

118

119
        /**
120
         * Stops monitoring ancestors of specified type.
121
         * @param class-string<IComponent>  $type
122
         */
123
        final public function unmonitor(string $type): void
124
        {
UNCOV
125
                unset($this->monitors[$type]);
×
126
        }
127

128

129
        /********************* interface IComponent ****************d*g**/
130

131

132
        final public function getName(): ?string
133
        {
134
                return $this->name;
1✔
135
        }
136

137

138
        /**
139
         * Returns the parent container if any.
140
         */
141
        final public function getParent(): ?IContainer
142
        {
143
                return $this->parent;
1✔
144
        }
145

146

147
        /**
148
         * Sets or removes the parent of this component. This method is managed by containers and should
149
         * not be called by applications
150
         * @throws Nette\InvalidStateException
151
         * @internal
152
         */
153
        public function setParent(?IContainer $parent, ?string $name = null): static
1✔
154
        {
155
                if ($parent === null && $this->parent === null && $name !== null) {
1✔
UNCOV
156
                        $this->name = $name; // just rename
×
157
                        return $this;
×
158

159
                } elseif ($parent === $this->parent && $name === null) {
1✔
UNCOV
160
                        return $this; // nothing to do
×
161
                }
162

163
                // A component cannot be given a parent if it already has a parent.
164
                if ($this->parent !== null && $parent !== null) {
1✔
165
                        throw new Nette\InvalidStateException("Component '$this->name' already has a parent.");
1✔
166
                }
167

168
                // remove from parent
169
                if ($parent === null) {
1✔
170
                        $this->refreshMonitors(0);
1✔
171
                        $this->parent = null;
1✔
172

173
                } else { // add to parent
174
                        $this->validateParent($parent);
1✔
175
                        $this->parent = $parent;
1✔
176
                        if ($name !== null) {
1✔
177
                                $this->name = $name;
1✔
178
                        }
179

180
                        $tmp = [];
1✔
181
                        $this->refreshMonitors(0, $tmp);
1✔
182
                }
183

184
                return $this;
1✔
185
        }
186

187

188
        /**
189
         * Validates the new parent before it's set.
190
         * Descendant classes can override this to implement custom validation logic.
191
         * @throws Nette\InvalidStateException
192
         */
193
        protected function validateParent(IContainer $parent): void
1✔
194
        {
195
        }
1✔
196

197

198
        /**
199
         * Refreshes monitors when attaching/detaching from component tree.
200
         * @param  ?array<string, true>  $missing  null = detaching, array = attaching
201
         * @param  array<array{\Closure, int}>  $called  deduplication tracking
202
         * @param  array<int, true>  $processed  prevents reentry
203
         */
204
        private function refreshMonitors(
1✔
205
                int $depth,
206
                ?array &$missing = null,
207
                array &$called = [],
208
                array &$processed = [],
209
        ): void
210
        {
211
                $processed[spl_object_id($this)] = true;
1✔
212

213
                if ($missing !== null) { // attaching
1✔
214
                        foreach ($this->monitors as $type => [$ancestor, , , $callbacks]) {
1✔
215
                                if (isset($ancestor)) { // already cached and valid - skip
1✔
216
                                        continue;
1✔
217

218
                                } elseif (!$callbacks) { // no listeners, just old cached lookup - clear it
1✔
UNCOV
219
                                        unset($this->monitors[$type]);
×
220

221
                                } elseif (isset($missing[$type])) { // already checked during this attach operation - ancestor not found
1✔
UNCOV
222
                                        $this->monitors[$type] = [null, null, null, $callbacks]; // keep listener registrations but clear cache
×
223

224
                                } else { // need to check if ancestor exists
225
                                        unset($this->monitors[$type]); // force fresh lookup
1✔
226
                                        assert($type !== '');
227
                                        if ($ancestor = $this->lookup($type, throw: false)) {
1✔
228
                                                foreach ($callbacks as [$attached]) {
1✔
229
                                                        if ($attached && !in_array($key = [$attached, spl_object_id($ancestor)], $called, strict: false)) {
1✔
230
                                                                $attached($ancestor);
1✔
231
                                                                $called[] = $key; // Deduplicate: same callback + same object = call once
1✔
232
                                                        }
233
                                                }
234
                                        } else {
235
                                                $missing[$type] = true; // ancestor not found - remember so we don't check again
1✔
236
                                        }
237

238
                                        $this->monitors[$type][3] = $callbacks; // restore listener (lookup() cached result in $this->monitors[$type])
1✔
239
                                }
240
                        }
241
                }
242

243
                if ($this instanceof IContainer) {
1✔
244
                        foreach ($this->getComponents() as $component) {
1✔
245
                                if ($component instanceof self
1✔
246
                                        && !isset($processed[spl_object_id($component)]) // component may have been processed already
1✔
247
                                        && $component->getParent() === $this  // may have been removed by previous sibling's listener
1✔
248
                                ) {
249
                                        $component->refreshMonitors($depth + 1, $missing, $called, $processed);
1✔
250
                                }
251
                        }
252
                }
253

254
                if ($missing === null) { // detaching
1✔
255
                        foreach ($this->monitors as $type => [$ancestor, $inDepth, , $callbacks]) {
1✔
256
                                if (isset($inDepth) && $inDepth > $depth) { // only process if ancestor was deeper than current detachment point
1✔
257
                                        assert($ancestor !== null);
258
                                        if ($callbacks) {
1✔
259
                                                $this->monitors[$type] = [null, null, null, $callbacks]; // clear cached object, keep listener registrations
1✔
260
                                                foreach ($callbacks as [, $detached]) {
1✔
261
                                                        if ($detached && !in_array($key = [$detached, spl_object_id($ancestor)], $called, strict: false)) {
1✔
262
                                                                $detached($ancestor);
1✔
263
                                                                $called[] = $key; // Deduplicate: same callback + same object = call once
1✔
264
                                                        }
265
                                                }
266
                                        } else { // no listeners, just cached lookup result - clear it
267
                                                unset($this->monitors[$type]);
1✔
268
                                        }
269
                                }
270
                        }
271
                }
272
        }
1✔
273

274

275
        /********************* cloneable, serializable ****************d*g**/
276

277

278
        /**
279
         * Object cloning.
280
         */
281
        public function __clone()
282
        {
283
                if ($this->parent === null) {
1✔
UNCOV
284
                        return;
×
285

286
                } elseif ($this->parent instanceof Container) {
1✔
287
                        $this->parent = $this->parent->_isCloning();
1✔
288
                        if ($this->parent === null) { // not cloning
1✔
289
                                $this->refreshMonitors(0);
1✔
290
                        }
291
                } else {
UNCOV
292
                        $this->parent = null;
×
UNCOV
293
                        $this->refreshMonitors(0);
×
294
                }
295
        }
1✔
296

297

298
        /**
299
         * Prevents serialization.
300
         */
301
        final public function __serialize()
302
        {
UNCOV
303
                throw new Nette\NotImplementedException('Object serialization is not supported by class ' . static::class);
×
304
        }
305
}
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