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

nette / component-model / 21201303594

21 Jan 2026 07:41AM UTC coverage: 87.156%. Remained the same
21201303594

push

github

dg
made static analysis mandatory

190 of 218 relevant lines covered (87.16%)

0.87 hits per line

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

88.79
/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 func_num_args, 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
 * @property-read string $name
20
 * @property-read ?IContainer $parent
21
 */
22
abstract class Component implements IComponent
23
{
24
        use Nette\SmartObject;
25

26
        private ?IContainer $parent = null;
27
        private ?string $name = null;
28

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

38
        /** Prevents nested listener execution during refreshMonitors */
39
        private bool $callingListeners = false;
40

41

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

62
                                $path = self::NameSeparator . $ancestor->getName() . $path;
1✔
63
                                $depth++;
1✔
64
                                $ancestor = $parent; // IComponent::getParent()
1✔
65
                                if ($ancestor === $this) {
1✔
66
                                        $ancestor = null; // prevent cycling
×
67
                                }
68
                        }
69

70
                        $this->monitors[$type] = $ancestor
1✔
71
                                ? [$ancestor, $depth, substr($path, 1), null]
1✔
72
                                : [null, null, null, null]; // not found
1✔
73
                }
74

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

80
                return $this->monitors[$type][0];
1✔
81
        }
82

83

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

97

98
        /**
99
         * Starts monitoring ancestors for attach/detach events.
100
         * @template T of IComponent
101
         * @param class-string<T>  $type
102
         * @param ?(callable(T): void)  $attached  called when attached to a monitored ancestor
103
         * @param ?(callable(T): void)  $detached  called before detaching from a monitored ancestor
104
         */
105
        final public function monitor(string $type, ?callable $attached = null, ?callable $detached = null): void
1✔
106
        {
107
                if (func_num_args() === 1) {
1✔
108
                        $attached = $this->attached(...);
1✔
109
                        $detached = $this->detached(...);
1✔
110
                }
111

112
                $ancestor = $this->lookup($type, throw: false);
1✔
113
                $this->monitors[$type][3] ??= [[], []];
1✔
114

115
                if ($attached && !in_array($attached(...), $this->monitors[$type][3][0], strict: false)) {
1✔
116
                        $this->monitors[$type][3][0][] = $attached(...);
1✔
117
                        if ($ancestor) {
1✔
118
                                $attached($ancestor);
1✔
119
                        }
120
                }
121

122
                if ($detached) {
1✔
123
                        $this->monitors[$type][3][1][] = $detached(...);
1✔
124
                }
125
        }
1✔
126

127

128
        /**
129
         * Stops monitoring ancestors of specified type.
130
         * @param class-string<IComponent>  $type
131
         */
132
        final public function unmonitor(string $type): void
133
        {
134
                unset($this->monitors[$type]);
×
135
        }
136

137

138
        /**
139
         * This method will be called when the component (or component's parent)
140
         * becomes attached to a monitored object. Do not call this method yourself.
141
         * @deprecated  use monitor($type, $attached)
142
         */
143
        protected function attached(IComponent $obj): void
144
        {
145
        }
146

147

148
        /**
149
         * This method will be called before the component (or component's parent)
150
         * becomes detached from a monitored object. Do not call this method yourself.
151
         * @deprecated  use monitor($type, null, $detached)
152
         */
153
        protected function detached(IComponent $obj): void
154
        {
155
        }
156

157

158
        /********************* interface IComponent ****************d*g**/
159

160

161
        final public function getName(): ?string
162
        {
163
                return $this->name;
1✔
164
        }
165

166

167
        /**
168
         * Returns the parent container if any.
169
         */
170
        final public function getParent(): ?IContainer
171
        {
172
                return $this->parent;
1✔
173
        }
174

175

176
        /**
177
         * Sets or removes the parent of this component. This method is managed by containers and should
178
         * not be called by applications
179
         * @throws Nette\InvalidStateException
180
         * @internal
181
         */
182
        public function setParent(?IContainer $parent, ?string $name = null): static
1✔
183
        {
184
                if ($parent === null && $this->parent === null && $name !== null) {
1✔
185
                        $this->name = $name; // just rename
×
186
                        return $this;
×
187

188
                } elseif ($parent === $this->parent && $name === null) {
1✔
189
                        return $this; // nothing to do
×
190
                }
191

192
                // A component cannot be given a parent if it already has a parent.
193
                if ($this->parent !== null && $parent !== null) {
1✔
194
                        throw new Nette\InvalidStateException("Component '$this->name' already has a parent.");
1✔
195
                }
196

197
                // remove from parent
198
                if ($parent === null) {
1✔
199
                        $this->refreshMonitors(0);
1✔
200
                        $this->parent = null;
1✔
201

202
                } else { // add to parent
203
                        $this->validateParent($parent);
1✔
204
                        $this->parent = $parent;
1✔
205
                        if ($name !== null) {
1✔
206
                                $this->name = $name;
1✔
207
                        }
208

209
                        $tmp = [];
1✔
210
                        $this->refreshMonitors(0, $tmp);
1✔
211
                }
212

213
                return $this;
1✔
214
        }
215

216

217
        /**
218
         * Validates the new parent before it's set.
219
         * Descendant classes can override this to implement custom validation logic.
220
         * @throws Nette\InvalidStateException
221
         */
222
        protected function validateParent(IContainer $parent): void
1✔
223
        {
224
        }
1✔
225

226

227
        /**
228
         * Refreshes monitors.
229
         * @param  ?array<string, true>  $missing  (array = attaching, null = detaching)
230
         * @param  array<int, array{\Closure, IComponent}>  $listeners
231
         */
232
        private function refreshMonitors(int $depth, ?array &$missing = null, array &$listeners = []): void
1✔
233
        {
234
                if ($this instanceof IContainer) {
1✔
235
                        foreach ($this->getComponents() as $component) {
1✔
236
                                if ($component instanceof self) {
1✔
237
                                        $component->refreshMonitors($depth + 1, $missing, $listeners);
1✔
238
                                }
239
                        }
240
                }
241

242
                if ($missing === null) { // detaching
1✔
243
                        foreach ($this->monitors as $type => [$ancestor, $inDepth, , $callbacks]) {
1✔
244
                                if (isset($inDepth) && $inDepth > $depth) { // only process if ancestor was deeper than current detachment point
1✔
245
                                        assert($ancestor !== null);
246
                                        if ($callbacks) {
1✔
247
                                                $this->monitors[$type] = [null, null, null, $callbacks]; // clear cached object, keep listener registrations
1✔
248
                                                foreach ($callbacks[1] as $detached) {
1✔
249
                                                        $listeners[] = [$detached, $ancestor];
1✔
250
                                                }
251
                                        } else { // no listeners, just cached lookup result - clear it
252
                                                unset($this->monitors[$type]);
×
253
                                        }
254
                                }
255
                        }
256
                } else { // attaching
257
                        foreach ($this->monitors as $type => [$ancestor, , , $callbacks]) {
1✔
258
                                if (isset($ancestor)) { // already cached and valid - skip
1✔
259
                                        continue;
1✔
260

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

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

267
                                } else { // need to check if ancestor exists
268
                                        unset($this->monitors[$type]); // force fresh lookup
1✔
269
                                        assert($type !== '');
270
                                        if ($ancestor = $this->lookup($type, throw: false)) {
1✔
271
                                                foreach ($callbacks[0] as $attached) {
1✔
272
                                                        $listeners[] = [$attached, $ancestor];
1✔
273
                                                }
274
                                        } else {
275
                                                $missing[$type] = true; // ancestor not found - remember so we don't check again
1✔
276
                                        }
277

278
                                        $this->monitors[$type][3] = $callbacks; // restore listener (lookup() cached result in $this->monitors[$type])
1✔
279
                                }
280
                        }
281
                }
282

283
                if ($depth === 0 && !$this->callingListeners) { // call listeners
1✔
284
                        $this->callingListeners = true;
1✔
285
                        try {
286
                                $called = [];
1✔
287
                                foreach ($listeners as [$callback, $component]) {
1✔
288
                                        if (!in_array($key = [$callback, spl_object_id($component)], $called, strict: false)) { // deduplicate: same callback + same object = call once
1✔
289
                                                $callback($component);
1✔
290
                                                $called[] = $key;
1✔
291
                                        }
292
                                }
293
                        } finally {
1✔
294
                                $this->callingListeners = false;
1✔
295
                        }
296
                }
297
        }
1✔
298

299

300
        /********************* cloneable, serializable ****************d*g**/
301

302

303
        /**
304
         * Object cloning.
305
         */
306
        public function __clone()
307
        {
308
                if ($this->parent === null) {
1✔
309
                        return;
×
310

311
                } elseif ($this->parent instanceof Container) {
1✔
312
                        $this->parent = $this->parent->_isCloning();
1✔
313
                        if ($this->parent === null) { // not cloning
1✔
314
                                $this->refreshMonitors(0);
1✔
315
                        }
316
                } else {
317
                        $this->parent = null;
×
318
                        $this->refreshMonitors(0);
×
319
                }
320
        }
1✔
321

322

323
        /**
324
         * Prevents serialization.
325
         */
326
        final public function __serialize()
327
        {
328
                throw new Nette\NotImplementedException('Object serialization is not supported by class ' . static::class);
×
329
        }
330
}
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