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

FunctionInvokerTrait::invokeFunction()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 25
Code Lines 15

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 25
ccs 11
cts 11
cp 1
rs 8.439
cc 5
eloc 15
nc 5
nop 2
crap 5
1
<?php
2
/**
3
 * FunctionInvokerTrait
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 ReflectionFunction;
17
18
/**
19
 * Trait to make the invokeFunction() 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 FunctionInvokerTrait
27
{
28
29
    /**
30
     * Check the accepted arguments for a given function and pass associative
31
     * array values in the right order.
32
     *
33
     * @since 0.1.0
34
     *
35
     * @param  string $function Name of the function to invoke.
36
     * @param  array  $args     Associative array that contains the arguments.
37
     * @return mixed            Return value of the invoked function.
38
     * @throws InvalidArgumentException If a valid function is missing.
39
     */
40 12
    public function invokeFunction($function, array $args = array())
41
    {
42
43 12
        if (! $function || ! is_string($function) || '' === $function) {
44 2
            throw new InvalidArgumentException(_('Missing valid function to invoke.'));
45
        }
46
47
        try {
48 10
            $reflection        = new ReflectionFunction($function);
49 9
            $ordered_arguments = Helper::parse_params(
50 9
                $reflection->getParameters(),
51
                $args
52
            );
53
54 8
            return $reflection->invokeArgs($ordered_arguments);
55 2
        } catch (Exception $exception) {
56 2
            throw new InvalidArgumentException(
57
                sprintf(
58 2
                    _('Failed to invoke function "%1$s". Reason: %2$s'),
59
                    $function,
60 2
                    $exception->getMessage()
61
                )
62
            );
63
        }
64
    }
65
}
66