| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCommunity\Framework\Support; |
| 4 |
|
| 5 |
use Closure; |
| 6 |
use RuntimeException; |
| 7 |
use ReflectionFunction; |
| 8 |
use FluentCommunity\Framework\Support\Helper; |
| 9 |
use FluentCommunity\Framework\Support\Reflector; |
| 10 |
|
| 11 |
trait ReflectsClosures |
| 12 |
{ |
| 13 |
/** |
| 14 |
* Get the class name of the first parameter of the given Closure. |
| 15 |
* |
| 16 |
* @param \Closure $closure |
| 17 |
* @return string |
| 18 |
* |
| 19 |
* @throws \ReflectionException |
| 20 |
* @throws \RuntimeException |
| 21 |
*/ |
| 22 |
protected function firstClosureParameterType(Closure $closure) |
| 23 |
{ |
| 24 |
$types = array_values($this->closureParameterTypes($closure)); |
| 25 |
|
| 26 |
if (! $types) { |
| 27 |
throw new RuntimeException('The given Closure has no parameters.'); |
| 28 |
} |
| 29 |
|
| 30 |
if ($types[0] === null) { |
| 31 |
throw new RuntimeException('The first parameter of the given Closure is missing a type hint.'); |
| 32 |
} |
| 33 |
|
| 34 |
return $types[0]; |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Get the class names of the first parameter of the given Closure, including union types. |
| 39 |
* |
| 40 |
* @param \Closure $closure |
| 41 |
* @return array |
| 42 |
* |
| 43 |
* @throws \ReflectionException |
| 44 |
* @throws \RuntimeException |
| 45 |
*/ |
| 46 |
protected function firstClosureParameterTypes(Closure $closure) |
| 47 |
{ |
| 48 |
$reflection = new ReflectionFunction($closure); |
| 49 |
|
| 50 |
$types = Helper::collect($reflection->getParameters())->mapWithKeys(function ($parameter) { |
| 51 |
if ($parameter->isVariadic()) { |
| 52 |
return [$parameter->getName() => null]; |
| 53 |
} |
| 54 |
|
| 55 |
return [$parameter->getName() => Reflector::getParameterClassNames($parameter)]; |
| 56 |
})->filter()->values()->all(); |
| 57 |
|
| 58 |
if (empty($types)) { |
| 59 |
throw new RuntimeException('The given Closure has no parameters.'); |
| 60 |
} |
| 61 |
|
| 62 |
if (isset($types[0]) && empty($types[0])) { |
| 63 |
throw new RuntimeException('The first parameter of the given Closure is missing a type hint.'); |
| 64 |
} |
| 65 |
|
| 66 |
return $types[0]; |
| 67 |
} |
| 68 |
|
| 69 |
/** |
| 70 |
* Get the class names / types of the parameters of the given Closure. |
| 71 |
* |
| 72 |
* @param \Closure $closure |
| 73 |
* @return array |
| 74 |
* |
| 75 |
* @throws \ReflectionException |
| 76 |
*/ |
| 77 |
protected function closureParameterTypes(Closure $closure) |
| 78 |
{ |
| 79 |
$reflection = new ReflectionFunction($closure); |
| 80 |
|
| 81 |
return Helper::collect($reflection->getParameters())->mapWithKeys(function ($parameter) { |
| 82 |
if ($parameter->isVariadic()) { |
| 83 |
return [$parameter->getName() => null]; |
| 84 |
} |
| 85 |
|
| 86 |
return [$parameter->getName() => Reflector::getParameterClassName($parameter)]; |
| 87 |
})->all(); |
| 88 |
} |
| 89 |
} |
| 90 |
|