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

nette / component-model / 21196676401

21 Jan 2026 03:57AM UTC coverage: 87.156%. Remained the same
21196676401

push

github

dg
added types tests

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<int, array{?\Closure, ?\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), []]
1✔
72
                                : [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
                } else {
111
                        $attached = $attached ? $attached(...) : null;
1✔
112
                        $detached = $detached ? $detached(...) : null;
1✔
113
                }
114

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

123
                $this->monitors[$type][3][] = [$attached, $detached]; // mark as monitored
1✔
124
        }
1✔
125

126

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

136

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

146

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

156

157
        /********************* interface IComponent ****************d*g**/
158

159

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

165

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

174

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

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

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

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

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

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

212
                return $this;
1✔
213
        }
214

215

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

225

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

241
                if ($missing === null) { // detaching
1✔
242
                        foreach ($this->monitors as $type => [$ancestor, $inDepth, , $callbacks]) {
1✔
243
                                if (isset($inDepth) && $inDepth > $depth) {
1✔
244
                                        assert($ancestor !== null);
245
                                        if ($callbacks) { // monitored
1✔
246
                                                $this->monitors[$type] = [null, null, null, $callbacks];
1✔
247
                                                foreach ($callbacks as [, $detached]) {
1✔
248
                                                        $listeners[] = [$detached, $ancestor];
1✔
249
                                                }
250
                                        } else { // not monitored, just randomly cached
251
                                                unset($this->monitors[$type]);
×
252
                                        }
253
                                }
254
                        }
255
                } else { // attaching
256
                        foreach ($this->monitors as $type => [$ancestor, , , $callbacks]) {
1✔
257
                                if (isset($ancestor)) { // is in cache yet
1✔
258
                                        continue;
1✔
259

260
                                } elseif (!$callbacks) { // not monitored, just randomly cached
1✔
261
                                        unset($this->monitors[$type]);
×
262

263
                                } elseif (isset($missing[$type])) { // known from previous lookup
1✔
264
                                        $this->monitors[$type] = [null, null, null, $callbacks];
×
265

266
                                } else {
267
                                        unset($this->monitors[$type]); // forces re-lookup
1✔
268
                                        assert($type !== '');
269
                                        if ($ancestor = $this->lookup($type, throw: false)) {
1✔
270
                                                foreach ($callbacks as [$attached]) {
1✔
271
                                                        $listeners[] = [$attached, $ancestor];
1✔
272
                                                }
273
                                        } else {
274
                                                $missing[$type] = true;
1✔
275
                                        }
276

277
                                        $this->monitors[$type][3] = $callbacks; // mark as monitored
1✔
278
                                }
279
                        }
280
                }
281

282
                if ($depth === 0 && !$this->callingListeners) { // call listeners
1✔
283
                        $this->callingListeners = true;
1✔
284
                        try {
285
                                $called = [];
1✔
286
                                foreach ($listeners as [$callback, $component]) {
1✔
287
                                        $key = [$callback, spl_object_id($component)];
1✔
288
                                        if ($callback && !in_array($key, $called, strict: false)) {
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