Passed
Push — master ( 84b57c...5992dd )
by Alain
02:16
created

MethodInvokerTrait::invokeMethod()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 26
ccs 11
cts 11
cp 1
rs 8.439
cc 5
eloc 16
nc 5
nop 3
crap 5
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