ReflectsClosures.php
2.47 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
<?php
namespace Illuminate\Support\Traits;
use Closure;
use Illuminate\Support\Reflector;
use ReflectionFunction;
use RuntimeException;
trait ReflectsClosures
{
/**
* Get the class name of the first parameter of the given Closure.
*
* @param \Closure $closure
* @return string
*
* @throws \ReflectionException
* @throws \RuntimeException
*/
protected function firstClosureParameterType(Closure $closure)
{
$types = array_values($this->closureParameterTypes($closure));
if (! $types) {
throw new RuntimeException('The given Closure has no parameters.');
}
if ($types[0] === null) {
throw new RuntimeException('The first parameter of the given Closure is missing a type hint.');
}
return $types[0];
}
/**
* Get the class names of the first parameter of the given Closure, including union types.
*
* @param \Closure $closure
* @return array
*
* @throws \ReflectionException
* @throws \RuntimeException
*/
protected function firstClosureParameterTypes(Closure $closure)
{
$reflection = new ReflectionFunction($closure);
$types = collect($reflection->getParameters())->mapWithKeys(function ($parameter) {
if ($parameter->isVariadic()) {
return [$parameter->getName() => null];
}
return [$parameter->getName() => Reflector::getParameterClassNames($parameter)];
})->filter()->values()->all();
if (empty($types)) {
throw new RuntimeException('The given Closure has no parameters.');
}
if (isset($types[0]) && empty($types[0])) {
throw new RuntimeException('The first parameter of the given Closure is missing a type hint.');
}
return $types[0];
}
/**
* Get the class names / types of the parameters of the given Closure.
*
* @param \Closure $closure
* @return array
*
* @throws \ReflectionException
*/
protected function closureParameterTypes(Closure $closure)
{
$reflection = new ReflectionFunction($closure);
return collect($reflection->getParameters())->mapWithKeys(function ($parameter) {
if ($parameter->isVariadic()) {
return [$parameter->getName() => null];
}
return [$parameter->getName() => Reflector::getParameterClassName($parameter)];
})->all();
}
}