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

nette / utils / 5706381664

pending completion
5706381664

push

github

dg
support for PHP 8.3

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

1863 of 2024 relevant lines covered (92.05%)

0.92 hits per line

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

92.9
/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

14

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

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

28

29
        /** @deprecated use Nette\Utils\Validator::isClassKeyword() */
30
        public static function isClassKeyword(string $name): bool
31
        {
32
                return Validators::isClassKeyword($name);
×
33
        }
34

35

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

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

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

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

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

67

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

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

85

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

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

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

118
                return $method;
×
119
        }
120

121

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

131

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

149

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

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

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

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

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

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

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

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

190

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

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

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

211

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

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

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

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

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

253
                                        break;
1✔
254

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

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

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

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

284
                                        break;
1✔
285

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

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

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

301
                return $res;
×
302
        }
303

304

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

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

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