1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Spiral\Core\Exception\Traits; |
6
|
|
|
|
7
|
|
|
use ReflectionNamedType; |
8
|
|
|
use ReflectionUnionType; |
9
|
|
|
|
10
|
|
|
trait ClosureRendererTrait |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @param string $pattern String that contains method and fileAndLine markers |
14
|
|
|
*/ |
15
|
35 |
|
protected function renderFunctionAndParameter( |
16
|
|
|
\ReflectionFunctionAbstract $reflection, |
17
|
|
|
string $pattern |
18
|
|
|
): string { |
19
|
35 |
|
$function = $reflection->getName(); |
20
|
|
|
/** @var class-string|null $class */ |
21
|
35 |
|
$class = $reflection->class ?? null; |
22
|
|
|
|
23
|
35 |
|
$method = match (true) { |
24
|
22 |
|
$class !== null => "{$class}::{$function}", |
25
|
13 |
|
$reflection->isClosure() => $this->renderClosureSignature($reflection), |
26
|
|
|
default => $function, |
27
|
35 |
|
}; |
28
|
|
|
|
29
|
35 |
|
$fileName = $reflection->getFileName(); |
30
|
35 |
|
$line = $reflection->getStartLine(); |
31
|
|
|
|
32
|
35 |
|
$fileAndLine = ''; |
33
|
35 |
|
if (!empty($fileName)) { |
34
|
35 |
|
$fileAndLine = "in \"$fileName\" at line $line"; |
35
|
|
|
} |
36
|
|
|
|
37
|
35 |
|
return \sprintf($pattern, $method, $fileAndLine); |
38
|
|
|
} |
39
|
|
|
|
40
|
745 |
|
private function renderClosureSignature(\ReflectionFunctionAbstract $reflection): string |
41
|
|
|
{ |
42
|
745 |
|
$closureParameters = []; |
43
|
|
|
|
44
|
745 |
|
foreach ($reflection->getParameters() as $parameter) { |
45
|
|
|
/** @var ReflectionNamedType|ReflectionUnionType|null $type */ |
46
|
743 |
|
$type = $parameter->getType(); |
47
|
743 |
|
$parameterString = \sprintf( |
48
|
743 |
|
'%s %s%s$%s', |
49
|
|
|
// type |
50
|
743 |
|
(string) $type, |
51
|
|
|
// reference |
52
|
743 |
|
$parameter->isPassedByReference() ? '&' : '', |
53
|
|
|
// variadic |
54
|
743 |
|
$parameter->isVariadic() ? '...' : '', |
55
|
743 |
|
$parameter->getName(), |
56
|
743 |
|
); |
57
|
743 |
|
if ($parameter->isDefaultValueAvailable()) { |
58
|
708 |
|
$default = $parameter->getDefaultValue(); |
59
|
|
|
$parameterString .= ' = ' . match (true) { |
60
|
708 |
|
\is_object($default) => 'new ' . $default::class . '(...)', |
61
|
687 |
|
$parameter->isDefaultValueConstant() => $parameter->getDefaultValueConstantName(), |
62
|
708 |
|
default => \var_export($default, true), |
63
|
|
|
}; |
64
|
|
|
} |
65
|
743 |
|
$closureParameters[] = \ltrim($parameterString); |
66
|
|
|
} |
67
|
745 |
|
$static = $reflection->isStatic() ? 'static ' : ''; |
|
|
|
|
68
|
745 |
|
return "{$static}function (" . \implode(', ', $closureParameters) . ')'; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|