-
-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathComponentReflection.php
More file actions
352 lines (294 loc) · 9.2 KB
/
ComponentReflection.php
File metadata and controls
352 lines (294 loc) · 9.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Application\UI;
use Nette;
/**
* Helpers for Presenter & Component.
* @property-deprecated string $name
* @property-deprecated string $fileName
* @internal
*/
final class ComponentReflection extends \ReflectionClass
{
private static array $ppCache = [];
private static array $pcCache = [];
private static array $mcCache = [];
/**
* Returns array of class properties that are public and have attribute #[Persistent] or #[Parameter].
*/
public function getParameters(): array
{
$params = &self::$ppCache[$this->getName()];
if ($params !== null) {
return $params;
}
$params = [];
$isPresenter = $this->isSubclassOf(Presenter::class);
foreach ($this->getProperties(\ReflectionProperty::IS_PUBLIC) as $prop) {
if ($prop->isStatic()) {
continue;
} elseif (
self::parseAnnotation($prop, 'persistent')
|| $prop->getAttributes(Nette\Application\Attributes\Persistent::class)
) {
$params[$prop->getName()] = [
'def' => $prop->getDefaultValue(),
'type' => self::getType($prop),
'since' => $isPresenter ? Nette\Utils\Reflection::getPropertyDeclaringClass($prop)->getName() : null,
];
} elseif ($prop->getAttributes(Nette\Application\Attributes\Parameter::class)) {
$params[$prop->getName()] = [
'type' => (string) ($prop->getType() ?? 'mixed'),
];
}
}
if ($this->getParentClass()->isSubclassOf(Component::class)) {
$parent = new self($this->getParentClass()->getName());
foreach ($parent->getParameters() as $name => $meta) {
if (!isset($params[$name])) {
$params[$name] = $meta;
} elseif (array_key_exists('since', $params[$name])) {
$params[$name]['since'] = $meta['since'];
}
}
}
return $params;
}
/**
* Returns array of persistent properties. They are public and have attribute #[Persistent].
*/
public function getPersistentParams(): array
{
return array_filter($this->getParameters(), fn($param) => array_key_exists('since', $param));
}
public function getPersistentComponents(): array
{
$class = $this->getName();
$components = &self::$pcCache[$class];
if ($components !== null) {
return $components;
}
$components = [];
if ($this->isSubclassOf(Presenter::class)) {
foreach ($class::getPersistentComponents() as $name => $meta) {
$components[is_string($meta) ? $meta : $name] = ['since' => $class];
}
$parent = new self($this->getParentClass()->getName());
$components = $parent->getPersistentComponents() + $components;
}
return $components;
}
/**
* Saves state information for next request.
*/
public function saveState(Component $component, array &$params): void
{
$tree = self::getClassesAndTraits($component::class);
foreach ($this->getPersistentParams() as $name => $meta) {
if (isset($params[$name])) {
// injected value
} elseif (
array_key_exists($name, $params) // nulls are skipped
|| (isset($meta['since']) && !isset($tree[$meta['since']])) // not related
|| !isset($component->$name)
) {
continue;
} else {
$params[$name] = $component->$name; // object property value
}
if (!self::convertType($params[$name], $meta['type'])) {
throw new InvalidLinkException(sprintf(
"Value passed to persistent parameter '%s' in %s must be %s, %s given.",
$name,
$component instanceof Presenter ? 'presenter ' . $component->getName() : "component '{$component->getUniqueId()}'",
$meta['type'],
get_debug_type($params[$name]),
));
}
if ($params[$name] === $meta['def'] || ($meta['def'] === null && $params[$name] === '')) {
$params[$name] = null; // value transmit is unnecessary
}
}
}
/**
* Is a method callable? It means class is instantiable and method has
* public visibility, is non-static and non-abstract.
*/
public function hasCallableMethod(string $method): bool
{
$class = $this->getName();
$cache = &self::$mcCache[strtolower($class . ':' . $method)];
if ($cache === null) {
try {
$cache = false;
$rm = new \ReflectionMethod($class, $method);
$cache = $this->isInstantiable() && $rm->isPublic() && !$rm->isAbstract() && !$rm->isStatic();
} catch (\ReflectionException) {
}
}
return $cache;
}
public static function combineArgs(\ReflectionFunctionAbstract $method, array $args): array
{
$res = [];
foreach ($method->getParameters() as $i => $param) {
$name = $param->getName();
$type = self::getType($param);
if (isset($args[$name])) {
$res[$i] = $args[$name];
if (!self::convertType($res[$i], $type)) {
throw new Nette\InvalidArgumentException(sprintf(
'Argument $%s passed to %s() must be %s, %s given.',
$name,
($method instanceof \ReflectionMethod ? $method->getDeclaringClass()->getName() . '::' : '') . $method->getName(),
$type,
get_debug_type($args[$name]),
));
}
} elseif ($param->isDefaultValueAvailable()) {
$res[$i] = $param->getDefaultValue();
} elseif ($type === 'scalar' || $param->allowsNull()) {
$res[$i] = null;
} elseif ($type === 'array' || $type === 'iterable') {
$res[$i] = [];
} else {
throw new Nette\InvalidArgumentException(sprintf(
'Missing parameter $%s required by %s()',
$name,
($method instanceof \ReflectionMethod ? $method->getDeclaringClass()->getName() . '::' : '') . $method->getName(),
));
}
}
return $res;
}
/**
* Lossless type conversion.
*/
public static function convertType(mixed &$val, string $types): bool
{
$scalars = ['string' => 1, 'int' => 1, 'float' => 1, 'bool' => 1, 'true' => 1, 'false' => 1];
$testable = ['iterable' => 1, 'object' => 1, 'array' => 1, 'null' => 1];
foreach (explode('|', ltrim($types, '?')) as $type) {
if (match (true) {
isset($scalars[$type]) => self::castScalar($val, $type),
isset($testable[$type]) => "is_$type"($val),
$type === 'scalar' => !is_array($val), // special type due to historical reasons
$type === 'mixed' => true,
$type === 'callable' => false, // intentionally disabled for security reasons
default => $val instanceof $type,
}) {
return true;
}
}
return false;
}
/**
* Lossless type casting.
*/
private static function castScalar(mixed &$val, string $type): bool
{
if (!is_scalar($val)) {
return false;
}
$tmp = ($val === false ? '0' : (string) $val);
if ($type === 'float') {
$tmp = preg_replace('#\.0*$#D', '', $tmp);
}
$orig = $tmp;
$spec = ['true' => true, 'false' => false];
isset($spec[$type]) ? $tmp = $spec[$type] : settype($tmp, $type);
if ($orig !== ($tmp === false ? '0' : (string) $tmp)) {
return false; // data-loss occurs
}
$val = $tmp;
return true;
}
/**
* Returns an annotation value.
* @deprecated
*/
public static function parseAnnotation(\Reflector $ref, string $name): ?array
{
if (!preg_match_all('#[\s*]@' . preg_quote($name, '#') . '(?:\(\s*([^)]*)\s*\)|\s|$)#', (string) $ref->getDocComment(), $m)) {
return null;
}
$tokens = ['true' => true, 'false' => false, 'null' => null];
$res = [];
foreach ($m[1] as $s) {
foreach (preg_split('#\s*,\s*#', $s, -1, PREG_SPLIT_NO_EMPTY) ?: ['true'] as $item) {
$res[] = array_key_exists($tmp = strtolower($item), $tokens)
? $tokens[$tmp]
: $item;
}
}
$attr = match ($name) {
'persistent' => '#[Nette\Application\Attributes\Persistent]',
'deprecated' => '#[Nette\Application\Attributes\Deprecated]',
'crossOrigin' => '#[Nette\Application\Attributes\Request(sameOrigin: false)]',
};
trigger_error("Annotation @$name is deprecated, use $attr (used in " . Nette\Utils\Reflection::toString($ref) . ')', E_USER_DEPRECATED);
return $res;
}
public static function getType(\ReflectionParameter|\ReflectionProperty $item): string
{
if ($type = $item->getType()) {
return (string) $type;
}
$default = $item instanceof \ReflectionProperty || $item->isDefaultValueAvailable()
? $item->getDefaultValue()
: null;
return $default === null ? 'scalar' : get_debug_type($default);
}
/**
* Has class specified annotation?
* @deprecated
*/
public function hasAnnotation(string $name): bool
{
return (bool) self::parseAnnotation($this, $name);
}
/**
* Returns an annotation value.
* @deprecated
*/
public function getAnnotation(string $name): mixed
{
$res = self::parseAnnotation($this, $name);
return $res ? end($res) : null;
}
public function getMethod($name): MethodReflection
{
return new MethodReflection($this->getName(), $name);
}
/**
* @return MethodReflection[]
*/
public function getMethods($filter = -1): array
{
foreach ($res = parent::getMethods($filter) as $key => $val) {
$res[$key] = new MethodReflection($this->getName(), $val->getName());
}
return $res;
}
/**
* return string[]
*/
public static function getClassesAndTraits(string $class): array
{
$res = [$class => $class] + class_parents($class);
$addTraits = function (string $type) use (&$res, &$addTraits): void {
$res += class_uses($type);
foreach (class_uses($type) as $trait) {
$addTraits($trait);
}
};
foreach ($res as $type) {
$addTraits($type);
}
return $res;
}
}