|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* MethodInvokerTrait |
|
4
|
|
|
* |
|
5
|
|
|
* @package BrightNucleus\Invoker |
|
6
|
|
|
* @author Alain Schlesser <[email protected]> |
|
7
|
|
|
* @license GPL-2.0+ |
|
8
|
|
|
* @link http://www.brightnucleus.com/ |
|
9
|
|
|
* @copyright 2015-2016 Alain Schlesser, Bright Nucleus |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace BrightNucleus\Invoker; |
|
13
|
|
|
|
|
14
|
|
|
use BrightNucleus\Exception\InvalidArgumentException; |
|
15
|
|
|
use Exception; |
|
16
|
|
|
use ReflectionMethod; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* Trait to make the invokeMethod() method easily accessible inside classes. |
|
20
|
|
|
* |
|
21
|
|
|
* @since 0.1.0 |
|
22
|
|
|
* |
|
23
|
|
|
* @package BrightNucleus\Invoker |
|
24
|
|
|
* @author Alain Schlesser <[email protected]> |
|
25
|
|
|
*/ |
|
26
|
|
|
trait MethodInvokerTrait |
|
27
|
|
|
{ |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* Check the accepted arguments for a given method and pass associative |
|
31
|
|
|
* array values in the right order. |
|
32
|
|
|
* |
|
33
|
|
|
* @since 0.1.0 |
|
34
|
|
|
* |
|
35
|
|
|
* @param object $object The object that contains the method to invoke. |
|
36
|
|
|
* @param string $method Name of the method to invoke. |
|
37
|
|
|
* @param array $args Associative array that contains the arguments. |
|
38
|
|
|
* @return mixed Return value of the invoked method. |
|
39
|
|
|
* @throws InvalidArgumentException If a valid method is missing. |
|
40
|
|
|
*/ |
|
41
|
12 |
|
protected function invokeMethod($object, $method, array $args = []) |
|
42
|
|
|
{ |
|
43
|
|
|
|
|
44
|
12 |
|
if (! $method || ! is_string($method) || '' === $method) { |
|
45
|
2 |
|
throw new InvalidArgumentException(_('Missing valid method to invoke.')); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
try { |
|
49
|
10 |
|
$reflection = new ReflectionMethod(get_class($object), $method); |
|
50
|
9 |
|
$ordered_arguments = Helper::parse_params( |
|
51
|
9 |
|
$reflection->getParameters(), |
|
52
|
|
|
$args |
|
53
|
|
|
); |
|
54
|
|
|
|
|
55
|
8 |
|
return $reflection->invokeArgs($object, $ordered_arguments); |
|
56
|
2 |
|
} catch (Exception $exception) { |
|
57
|
2 |
|
throw new InvalidArgumentException( |
|
58
|
|
|
sprintf( |
|
59
|
2 |
|
_('Failed to invoke method "%1$s" of class "%2$s". Reason: %3$s'), |
|
60
|
|
|
$method, |
|
61
|
|
|
get_class($object), |
|
62
|
2 |
|
$exception->getMessage() |
|
63
|
|
|
) |
|
64
|
|
|
); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|