1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Selami\Stdlib; |
6
|
|
|
|
7
|
|
|
use ReflectionException; |
8
|
|
|
use ReflectionMethod; |
9
|
|
|
use ReflectionParameter; |
10
|
|
|
use Selami\Stdlib\Exception\ClassOrMethodCouldNotBeFound; |
11
|
|
|
|
12
|
|
|
use function assert; |
13
|
|
|
use function class_exists; |
14
|
|
|
use function is_array; |
15
|
|
|
use function method_exists; |
16
|
|
|
use function sprintf; |
17
|
|
|
|
18
|
|
|
class Resolver |
19
|
|
|
{ |
20
|
|
|
public const ARRAY = 'array'; |
21
|
|
|
public const CALLABLE = 'callable'; |
22
|
|
|
public const BOOLEAN = 'boolean'; |
23
|
|
|
public const FLOAT = 'float'; |
24
|
|
|
public const INTEGER = 'int'; |
25
|
|
|
public const STRING = 'string'; |
26
|
|
|
public const ITERABLE = 'iterable'; |
27
|
|
|
|
28
|
|
|
public static function getParameterHints(string $className, string $methodName): array |
29
|
|
|
{ |
30
|
|
|
self::checkClassName($className); |
31
|
|
|
self::checkMethodName($className, $methodName); |
32
|
|
|
try { |
33
|
|
|
$method = new ReflectionMethod($className, $methodName); |
34
|
|
|
} catch (ReflectionException $e) { |
35
|
|
|
throw new ClassOrMethodCouldNotBeFound( |
36
|
|
|
sprintf('%s::%s coulnd not be found.', $className, $methodName) |
37
|
|
|
); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
$parameters = $method->getParameters(); |
41
|
|
|
assert(is_array($parameters)); |
42
|
|
|
$parameterHints = []; |
43
|
|
|
foreach ($parameters as $param) { |
44
|
|
|
$parameter = self::getParamType($param); |
45
|
|
|
$parameterHints[$parameter['name']] = $parameter['type']; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
return $parameterHints; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
private static function checkClassName(string $className): void |
52
|
|
|
{ |
53
|
|
|
if (! class_exists($className)) { |
54
|
|
|
throw new ClassOrMethodCouldNotBeFound( |
55
|
|
|
sprintf('%s class does not exist!', $className) |
56
|
|
|
); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
private static function checkMethodName(string $className, string $methodName): void |
61
|
|
|
{ |
62
|
|
|
if (! method_exists($className, $methodName)) { |
63
|
|
|
throw new ClassOrMethodCouldNotBeFound( |
64
|
|
|
sprintf('%s does not have method named %s!', $className, $methodName) |
65
|
|
|
); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
private static function getParamType(ReflectionParameter $parameter): array |
70
|
|
|
{ |
71
|
|
|
$type = $parameter->getType(); |
72
|
|
|
if ($type->isBuiltin()) { |
73
|
|
|
return ['name' => $parameter->name, 'type' => $type->getName()]; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
try { |
77
|
|
|
return ['name' => $parameter->name, 'type' => $type->getName()]; |
78
|
|
|
} catch (ReflectionException $e) { |
79
|
|
|
throw new ClassOrMethodCouldNotBeFound($e->getMessage()); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|