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
|
|
|
if (is_array($callable)) { // [class, method] |
52
|
|
|
$reflector = new \ReflectionClass($callable[0]); |
53
|
|
|
$method = $reflector->getMethod($callable[1]); |
54
|
|
|
} elseif (is_string($callable) || $callable instanceof \Closure) { // function |
55
|
|
|
$method = new \ReflectionFunction($callable); |
56
|
|
|
} else { // __invokable |
57
|
|
|
$reflector = new \ReflectionClass($callable); |
58
|
|
|
$method = $reflector->getMethod('__invoke'); |
59
|
|
|
} |
60
|
|
|
} catch (\Throwable $e) { |
61
|
|
|
throw new \InvalidArgumentException($e->getMessage()); |
62
|
|
|
} |
63
|
|
|
return $method->getParameters(); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|