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

nette / component-model / 21201310637

21 Jan 2026 07:42AM UTC coverage: 87.444%. Remained the same
21201310637

push

github

dg
used attribute Deprecated

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

88.99
/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-deprecated string $name
20
 * @property-deprecated ?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
                        $class = (new \ReflectionMethod($this, 'attached'))->getDeclaringClass()->getName();
1✔
109
                        trigger_error(__METHOD__ . "(): Methods $class::attached() and $class::detached() are deprecated, use monitor(\$type, [attached], [detached])", E_USER_DEPRECATED);
1✔
110
                        $attached = $this->attached(...);
1✔
111
                        $detached = $this->detached(...);
1✔
112
                }
113

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

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

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

129

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

139

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

149

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

159

160
        /********************* interface IComponent ****************d*g**/
161

162

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

168

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

177

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

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

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

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

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

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

215
                return $this;
1✔
216
        }
217

218

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

228

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

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

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

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

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

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

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

301

302
        /********************* cloneable, serializable ****************d*g**/
303

304

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

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

324

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