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

nette / utils / 20431395313

22 Dec 2025 12:06PM UTC coverage: 93.164% (+71.8%) from 21.324%
20431395313

push

github

dg
Html::addText() accepts int|null for back compatibility [Closes #332][Closes #333]

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

140 existing lines in 15 files now uncovered.

2058 of 2209 relevant lines covered (93.16%)

0.93 hits per line

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

92.41
/src/Utils/Reflection.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\Utils;
11

12
use Nette;
13
use function constant, current, defined, end, explode, file_get_contents, implode, ltrim, next, ord, strrchr, strtolower, substr;
14
use const T_AS, T_CLASS, T_COMMENT, T_CURLY_OPEN, T_DOC_COMMENT, T_DOLLAR_OPEN_CURLY_BRACES, T_ENUM, T_INTERFACE, T_NAME_FULLY_QUALIFIED, T_NAME_QUALIFIED, T_NAMESPACE, T_NS_SEPARATOR, T_STRING, T_TRAIT, T_USE, T_WHITESPACE, TOKEN_PARSE;
15

16

17
/**
18
 * PHP reflection helpers.
19
 */
20
final class Reflection
21
{
22
        use Nette\StaticClass;
23

24
        /** @deprecated use Nette\Utils\Validators::isBuiltinType() */
25
        public static function isBuiltinType(string $type): bool
26
        {
UNCOV
27
                return Validators::isBuiltinType($type);
×
28
        }
29

30

31
        #[\Deprecated('use Nette\Utils\Validators::isClassKeyword()')]
32
        public static function isClassKeyword(string $name): bool
33
        {
UNCOV
34
                return Validators::isClassKeyword($name);
×
35
        }
36

37

38
        public static function getParameterDefaultValue(\ReflectionParameter $param): mixed
1✔
39
        {
40
                if ($param->isDefaultValueConstant()) {
1✔
41
                        $const = $orig = $param->getDefaultValueConstantName();
1✔
42
                        $pair = explode('::', $const);
1✔
43
                        if (isset($pair[1])) {
1✔
44
                                $pair[0] = Type::resolve($pair[0], $param);
1✔
45
                                try {
46
                                        $rcc = new \ReflectionClassConstant($pair[0], $pair[1]);
1✔
47
                                } catch (\ReflectionException $e) {
1✔
48
                                        $name = self::toString($param);
1✔
49
                                        throw new \ReflectionException("Unable to resolve constant $orig used as default value of $name.", 0, $e);
1✔
50
                                }
51

52
                                return $rcc->getValue();
1✔
53

54
                        } elseif (!defined($const)) {
1✔
55
                                $const = substr((string) strrchr($const, '\\'), 1);
1✔
56
                                if (!defined($const)) {
1✔
57
                                        $name = self::toString($param);
1✔
58
                                        throw new \ReflectionException("Unable to resolve constant $orig used as default value of $name.");
1✔
59
                                }
60
                        }
61

62
                        return constant($const);
1✔
63
                }
64

UNCOV
65
                return $param->getDefaultValue();
×
66
        }
67

68

69
        /**
70
         * Returns a reflection of a class or trait that contains a declaration of given property. Property can also be declared in the trait.
71
         */
72
        public static function getPropertyDeclaringClass(\ReflectionProperty $prop): \ReflectionClass
1✔
73
        {
74
                foreach ($prop->getDeclaringClass()->getTraits() as $trait) {
1✔
75
                        if ($trait->hasProperty($prop->name)
1✔
76
                                // doc-comment guessing as workaround for insufficient PHP reflection
77
                                && $trait->getProperty($prop->name)->getDocComment() === $prop->getDocComment()
1✔
78
                        ) {
79
                                return self::getPropertyDeclaringClass($trait->getProperty($prop->name));
1✔
80
                        }
81
                }
82

83
                return $prop->getDeclaringClass();
1✔
84
        }
85

86

87
        /**
88
         * Returns a reflection of a method that contains a declaration of $method.
89
         * Usually, each method is its own declaration, but the body of the method can also be in the trait and under a different name.
90
         */
91
        public static function getMethodDeclaringMethod(\ReflectionMethod $method): \ReflectionMethod
1✔
92
        {
93
                // file & line guessing as workaround for insufficient PHP reflection
94
                $decl = $method->getDeclaringClass();
1✔
95
                if ($decl->getFileName() === $method->getFileName()
1✔
96
                        && $decl->getStartLine() <= $method->getStartLine()
1✔
97
                        && $decl->getEndLine() >= $method->getEndLine()
1✔
98
                ) {
99
                        return $method;
1✔
100
                }
101

102
                $hash = [$method->getFileName(), $method->getStartLine(), $method->getEndLine()];
1✔
103
                if (($alias = $decl->getTraitAliases()[$method->name] ?? null)
1✔
104
                        && ($m = new \ReflectionMethod(...explode('::', $alias, 2)))
1✔
105
                        && $hash === [$m->getFileName(), $m->getStartLine(), $m->getEndLine()]
1✔
106
                ) {
107
                        return self::getMethodDeclaringMethod($m);
1✔
108
                }
109

110
                foreach ($decl->getTraits() as $trait) {
1✔
111
                        if ($trait->hasMethod($method->name)
1✔
112
                                && ($m = $trait->getMethod($method->name))
1✔
113
                                && $hash === [$m->getFileName(), $m->getStartLine(), $m->getEndLine()]
1✔
114
                        ) {
115
                                return self::getMethodDeclaringMethod($m);
1✔
116
                        }
117
                }
118

UNCOV
119
                return $method;
×
120
        }
121

122

123
        /**
124
         * Finds out if reflection has access to PHPdoc comments. Comments may not be available due to the opcode cache.
125
         */
126
        public static function areCommentsAvailable(): bool
127
        {
UNCOV
128
                static $res;
×
UNCOV
129
                return $res ?? $res = (bool) (new \ReflectionMethod(self::class, __FUNCTION__))->getDocComment();
×
130
        }
131

132

133
        public static function toString(\Reflector $ref): string
1✔
134
        {
135
                if ($ref instanceof \ReflectionClass) {
1✔
136
                        return $ref->name;
1✔
137
                } elseif ($ref instanceof \ReflectionMethod) {
1✔
138
                        return $ref->getDeclaringClass()->name . '::' . $ref->name . '()';
1✔
139
                } elseif ($ref instanceof \ReflectionFunction) {
1✔
140
                        return $ref->isAnonymous() ? '{closure}()' : $ref->name . '()';
1✔
141
                } elseif ($ref instanceof \ReflectionProperty) {
1✔
142
                        return self::getPropertyDeclaringClass($ref)->name . '::$' . $ref->name;
1✔
143
                } elseif ($ref instanceof \ReflectionParameter) {
1✔
144
                        return '$' . $ref->name . ' in ' . self::toString($ref->getDeclaringFunction());
1✔
145
                } else {
UNCOV
146
                        throw new Nette\InvalidArgumentException;
×
147
                }
148
        }
149

150

151
        /**
152
         * Expands the name of the class to full name in the given context of given class.
153
         * Thus, it returns how the PHP parser would understand $name if it were written in the body of the class $context.
154
         * @throws Nette\InvalidArgumentException
155
         */
156
        public static function expandClassName(string $name, \ReflectionClass $context): string
1✔
157
        {
158
                $lower = strtolower($name);
1✔
159
                if (empty($name)) {
1✔
160
                        throw new Nette\InvalidArgumentException('Class name must not be empty.');
1✔
161

162
                } elseif (Validators::isBuiltinType($lower)) {
1✔
163
                        return $lower;
1✔
164

165
                } elseif ($lower === 'self' || $lower === 'static') {
1✔
166
                        return $context->name;
1✔
167

168
                } elseif ($lower === 'parent') {
1✔
169
                        return $context->getParentClass()
1✔
170
                                ? $context->getParentClass()->name
1✔
171
                                : 'parent';
1✔
172

173
                } elseif ($name[0] === '\\') { // fully qualified name
1✔
174
                        return ltrim($name, '\\');
1✔
175
                }
176

177
                $uses = self::getUseStatements($context);
1✔
178
                $parts = explode('\\', $name, 2);
1✔
179
                if (isset($uses[$parts[0]])) {
1✔
180
                        $parts[0] = $uses[$parts[0]];
1✔
181
                        return implode('\\', $parts);
1✔
182

183
                } elseif ($context->inNamespace()) {
1✔
184
                        return $context->getNamespaceName() . '\\' . $name;
1✔
185

186
                } else {
187
                        return $name;
1✔
188
                }
189
        }
190

191

192
        /** @return array<string, class-string> of [alias => class] */
193
        public static function getUseStatements(\ReflectionClass $class): array
1✔
194
        {
195
                if ($class->isAnonymous()) {
1✔
196
                        throw new Nette\NotImplementedException('Anonymous classes are not supported.');
1✔
197
                }
198

199
                static $cache = [];
1✔
200
                if (!isset($cache[$name = $class->name])) {
1✔
201
                        if ($class->isInternal()) {
1✔
202
                                $cache[$name] = [];
1✔
203
                        } else {
204
                                $code = file_get_contents($class->getFileName());
1✔
205
                                $cache = self::parseUseStatements($code, $name) + $cache;
1✔
206
                        }
207
                }
208

209
                return $cache[$name];
1✔
210
        }
211

212

213
        /**
214
         * Parses PHP code to [class => [alias => class, ...]]
215
         */
216
        private static function parseUseStatements(string $code, ?string $forClass = null): array
1✔
217
        {
218
                try {
219
                        $tokens = \PhpToken::tokenize($code, TOKEN_PARSE);
1✔
UNCOV
220
                } catch (\ParseError $e) {
×
UNCOV
221
                        trigger_error($e->getMessage(), E_USER_NOTICE);
×
UNCOV
222
                        $tokens = [];
×
223
                }
224

225
                $namespace = $class = null;
1✔
226
                $classLevel = $level = 0;
1✔
227
                $res = $uses = [];
1✔
228

229
                $nameTokens = [T_STRING, T_NS_SEPARATOR, T_NAME_QUALIFIED, T_NAME_FULLY_QUALIFIED];
1✔
230

231
                while ($token = current($tokens)) {
1✔
232
                        next($tokens);
1✔
233
                        switch ($token->id) {
1✔
234
                                case T_NAMESPACE:
235
                                        $namespace = ltrim(self::fetch($tokens, $nameTokens) . '\\', '\\');
1✔
236
                                        $uses = [];
1✔
237
                                        break;
1✔
238

239
                                case T_CLASS:
240
                                case T_INTERFACE:
241
                                case T_TRAIT:
242
                                case T_ENUM:
243
                                        if ($name = self::fetch($tokens, T_STRING)) {
1✔
244
                                                $class = $namespace . $name;
1✔
245
                                                $classLevel = $level + 1;
1✔
246
                                                $res[$class] = $uses;
1✔
247
                                                if ($class === $forClass) {
1✔
248
                                                        return $res;
1✔
249
                                                }
250
                                        }
251

252
                                        break;
1✔
253

254
                                case T_USE:
255
                                        while (!$class && ($name = self::fetch($tokens, $nameTokens))) {
1✔
256
                                                $name = ltrim($name, '\\');
1✔
257
                                                if (self::fetch($tokens, '{')) {
1✔
258
                                                        while ($suffix = self::fetch($tokens, $nameTokens)) {
1✔
259
                                                                if (self::fetch($tokens, T_AS)) {
1✔
260
                                                                        $uses[self::fetch($tokens, T_STRING)] = $name . $suffix;
1✔
261
                                                                } else {
262
                                                                        $tmp = explode('\\', $suffix);
1✔
263
                                                                        $uses[end($tmp)] = $name . $suffix;
1✔
264
                                                                }
265

266
                                                                if (!self::fetch($tokens, ',')) {
1✔
267
                                                                        break;
1✔
268
                                                                }
269
                                                        }
270
                                                } elseif (self::fetch($tokens, T_AS)) {
1✔
271
                                                        $uses[self::fetch($tokens, T_STRING)] = $name;
1✔
272

273
                                                } else {
274
                                                        $tmp = explode('\\', $name);
1✔
275
                                                        $uses[end($tmp)] = $name;
1✔
276
                                                }
277

278
                                                if (!self::fetch($tokens, ',')) {
1✔
279
                                                        break;
1✔
280
                                                }
281
                                        }
282

283
                                        break;
1✔
284

285
                                case T_CURLY_OPEN:
286
                                case T_DOLLAR_OPEN_CURLY_BRACES:
287
                                case ord('{'):
1✔
288
                                        $level++;
1✔
289
                                        break;
1✔
290

291
                                case ord('}'):
1✔
292
                                        if ($level === $classLevel) {
1✔
293
                                                $class = $classLevel = 0;
1✔
294
                                        }
295

296
                                        $level--;
1✔
297
                        }
298
                }
299

UNCOV
300
                return $res;
×
301
        }
302

303

304
        private static function fetch(array &$tokens, string|int|array $take): ?string
1✔
305
        {
306
                $res = null;
1✔
307
                while ($token = current($tokens)) {
1✔
308
                        if ($token->is($take)) {
1✔
309
                                $res .= $token->text;
1✔
310
                        } elseif (!$token->is([T_DOC_COMMENT, T_WHITESPACE, T_COMMENT])) {
1✔
311
                                break;
1✔
312
                        }
313

314
                        next($tokens);
1✔
315
                }
316

317
                return $res;
1✔
318
        }
319
}
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