1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Phoole (PHP7.2+) |
5
|
|
|
* |
6
|
|
|
* @category Library |
7
|
|
|
* @package Phoole\Base |
8
|
|
|
* @copyright Copyright (c) 2019 Hong Zhang |
9
|
|
|
*/ |
10
|
|
|
declare(strict_types=1); |
11
|
|
|
|
12
|
|
|
namespace Phoole\Base\Reflect; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* ParameterTrait |
16
|
|
|
* |
17
|
|
|
* try get parameters of the callable / constructor etc. |
18
|
|
|
* |
19
|
|
|
* @package Phoole\Base |
20
|
|
|
*/ |
21
|
|
|
trait ParameterTrait |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* Get class/object constructor parameters |
25
|
|
|
* |
26
|
|
|
* @param string|object $class class name or object |
27
|
|
|
* @return \ReflectionParameter[] |
28
|
|
|
* @throws \InvalidArgumentException if something goes wrong |
29
|
|
|
*/ |
30
|
|
|
protected function getConstructorParameters($class): array |
31
|
|
|
{ |
32
|
|
|
try { |
33
|
|
|
$reflector = new \ReflectionClass($class); |
34
|
|
|
$constructor = $reflector->getConstructor(); |
35
|
|
|
return is_null($constructor) ? [] : $constructor->getParameters(); |
36
|
|
|
} catch (\Throwable $e) { |
37
|
|
|
throw new \InvalidArgumentException($e->getMessage()); |
38
|
|
|
} |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Get callable parameters |
43
|
|
|
* |
44
|
|
|
* @param callable $callable |
45
|
|
|
* @return \ReflectionParameter[] |
46
|
|
|
* @throws \InvalidArgumentException if something goes wrong |
47
|
|
|
*/ |
48
|
|
|
protected function getCallableParameters(callable $callable): array |
49
|
|
|
{ |
50
|
|
|
try { |
51
|
|
|
// [class, method] |
52
|
|
|
if (is_array($callable)) { |
53
|
|
|
$reflector = new \ReflectionClass($callable[0]); |
54
|
|
|
$method = $reflector->getMethod($callable[1]); |
55
|
|
|
|
56
|
|
|
// function or closure |
57
|
|
|
} elseif (is_string($callable) || $callable instanceof \Closure) { |
58
|
|
|
$method = new \ReflectionFunction($callable); |
59
|
|
|
|
60
|
|
|
// object with __invoke() defined |
61
|
|
|
} elseif (is_object($callable)) { |
62
|
|
|
$reflector = new \ReflectionClass($callable); |
63
|
|
|
$method = $reflector->getMethod('__invoke'); |
64
|
|
|
|
65
|
|
|
// unknown callable ? |
66
|
|
|
} else { |
67
|
|
|
throw new \InvalidArgumentException('unknown type of callable'); |
68
|
|
|
} |
69
|
|
|
} catch (\Throwable $e) { |
70
|
|
|
throw new \InvalidArgumentException($e->getMessage()); |
71
|
|
|
} |
72
|
|
|
return $method->getParameters(); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|