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