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

nette / utils / 21636962765

03 Feb 2026 03:39PM UTC coverage: 93.312% (+0.05%) from 93.264%
21636962765

push

github

dg
added CLAUDE.md

2065 of 2213 relevant lines covered (93.31%)

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
        {
27
                return Validators::isBuiltinType($type);
×
28
        }
29

30

31
        #[\Deprecated('use Nette\Utils\Validators::isClassKeyword()')]
32
        public static function isClassKeyword(string $name): bool
33
        {
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

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
         * @return \ReflectionClass<object>
72
         */
73
        public static function getPropertyDeclaringClass(\ReflectionProperty $prop): \ReflectionClass
1✔
74
        {
75
                foreach ($prop->getDeclaringClass()->getTraits() as $trait) {
1✔
76
                        if ($trait->hasProperty($prop->name)
1✔
77
                                // doc-comment guessing as workaround for insufficient PHP reflection
78
                                && $trait->getProperty($prop->name)->getDocComment() === $prop->getDocComment()
1✔
79
                        ) {
80
                                return self::getPropertyDeclaringClass($trait->getProperty($prop->name));
1✔
81
                        }
82
                }
83

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

87

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

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

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

120
                return $method;
×
121
        }
122

123

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

133

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

151

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

164
                } elseif (Validators::isBuiltinType($lower)) {
1✔
165
                        return $lower;
1✔
166

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

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

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

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

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

188
                } else {
189
                        return $name;
1✔
190
                }
191
        }
192

193

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

204
                static $cache = [];
1✔
205
                if (!isset($cache[$name = $class->name])) {
1✔
206
                        if ($class->isInternal()) {
1✔
207
                                $cache[$name] = [];
1✔
208
                        } else {
209
                                $code = file_get_contents($class->getFileName());
1✔
210
                                $cache = self::parseUseStatements($code, $name) + $cache;
1✔
211
                        }
212
                }
213

214
                return $cache[$name];
1✔
215
        }
216

217

218
        /**
219
         * Parses PHP code to [class => [alias => class, ...]]
220
         * @return array<class-string, array<string, class-string>>
221
         */
222
        private static function parseUseStatements(string $code, ?string $forClass = null): array
1✔
223
        {
224
                try {
225
                        $tokens = \PhpToken::tokenize($code, TOKEN_PARSE);
1✔
226
                } catch (\ParseError $e) {
×
227
                        trigger_error($e->getMessage(), E_USER_NOTICE);
×
228
                        $tokens = [];
×
229
                }
230

231
                $namespace = $class = null;
1✔
232
                $classLevel = $level = 0;
1✔
233
                $res = $uses = [];
1✔
234

235
                $nameTokens = [T_STRING, T_NS_SEPARATOR, T_NAME_QUALIFIED, T_NAME_FULLY_QUALIFIED];
1✔
236

237
                while ($token = current($tokens)) {
1✔
238
                        next($tokens);
1✔
239
                        switch ($token->id) {
1✔
240
                                case T_NAMESPACE:
241
                                        $namespace = ltrim(self::fetch($tokens, $nameTokens) . '\\', '\\');
1✔
242
                                        $uses = [];
1✔
243
                                        break;
1✔
244

245
                                case T_CLASS:
246
                                case T_INTERFACE:
247
                                case T_TRAIT:
248
                                case T_ENUM:
249
                                        if ($name = self::fetch($tokens, T_STRING)) {
1✔
250
                                                $class = $namespace . $name;
1✔
251
                                                $classLevel = $level + 1;
1✔
252
                                                $res[$class] = $uses;
1✔
253
                                                if ($class === $forClass) {
1✔
254
                                                        return $res;
1✔
255
                                                }
256
                                        }
257

258
                                        break;
1✔
259

260
                                case T_USE:
261
                                        while (!$class && ($name = self::fetch($tokens, $nameTokens))) {
1✔
262
                                                $name = ltrim($name, '\\');
1✔
263
                                                if (self::fetch($tokens, '{')) {
1✔
264
                                                        while ($suffix = self::fetch($tokens, $nameTokens)) {
1✔
265
                                                                if (self::fetch($tokens, T_AS)) {
1✔
266
                                                                        $uses[self::fetch($tokens, T_STRING)] = $name . $suffix;
1✔
267
                                                                } else {
268
                                                                        $tmp = explode('\\', $suffix);
1✔
269
                                                                        $uses[end($tmp)] = $name . $suffix;
1✔
270
                                                                }
271

272
                                                                if (!self::fetch($tokens, ',')) {
1✔
273
                                                                        break;
1✔
274
                                                                }
275
                                                        }
276
                                                } elseif (self::fetch($tokens, T_AS)) {
1✔
277
                                                        $uses[self::fetch($tokens, T_STRING)] = $name;
1✔
278

279
                                                } else {
280
                                                        $tmp = explode('\\', $name);
1✔
281
                                                        $uses[end($tmp)] = $name;
1✔
282
                                                }
283

284
                                                if (!self::fetch($tokens, ',')) {
1✔
285
                                                        break;
1✔
286
                                                }
287
                                        }
288

289
                                        break;
1✔
290

291
                                case T_CURLY_OPEN:
292
                                case T_DOLLAR_OPEN_CURLY_BRACES:
293
                                case ord('{'):
1✔
294
                                        $level++;
1✔
295
                                        break;
1✔
296

297
                                case ord('}'):
1✔
298
                                        if ($level === $classLevel) {
1✔
299
                                                $class = $classLevel = 0;
1✔
300
                                        }
301

302
                                        $level--;
1✔
303
                        }
304
                }
305

306
                return $res;
×
307
        }
308

309

310
        /**
311
         * @param  \PhpToken[]  $tokens
312
         * @param  string|int|int[]  $take
313
         */
314
        private static function fetch(array &$tokens, string|int|array $take): ?string
1✔
315
        {
316
                $res = null;
1✔
317
                while ($token = current($tokens)) {
1✔
318
                        if ($token->is($take)) {
1✔
319
                                $res .= $token->text;
1✔
320
                        } elseif (!$token->is([T_DOC_COMMENT, T_WHITESPACE, T_COMMENT])) {
1✔
321
                                break;
1✔
322
                        }
323

324
                        next($tokens);
1✔
325
                }
326

327
                return $res;
1✔
328
        }
329
}
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