Completed
Push — master ( ac0544...a10425 )
by Nate
11:46 queued 42s
created

ExtraParameterTrait::validParams()   C

Complexity

Conditions 7
Paths 11

Size

Total Lines 32
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
dl 0
loc 32
ccs 0
cts 28
cp 0
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 20
nc 11
nop 2
crap 56
1
<?php
2
3
/**
4
 * @author    Flipbox Factory
5
 * @copyright Copyright (c) 2017, Flipbox Digital
6
 * @link      https://github.com/flipbox/transform/releases/latest
7
 * @license   https://github.com/flipbox/transform/blob/master/LICENSE
8
 */
9
10
namespace Flipbox\Transform\Traits;
11
12
use InvalidArgumentException;
13
use ReflectionMethod;
14
use ReflectionParameter;
15
16
/**
17
 * @author Flipbox Factory <[email protected]>
18
 * @since 3.0.0
19
 */
20
trait ExtraParameterTrait
21
{
22
    /**
23
     * @param $transformer
24
     * @param array $params
25
     * @return array
26
     * @throws \ReflectionException
27
     */
28
    private function validParams($transformer, array $params): array
29
    {
30
        if (!is_object($transformer)) {
31
            return $params;
32
        }
33
34
        $method = new ReflectionMethod($transformer, '__invoke');
35
36
        $args = $missing = [];
37
        foreach ($method->getParameters() as $param) {
38
            $name = $param->name;
39
            if (true === in_array($name, ['data', 'scope', 'identifier'], true)) {
40
                continue;
41
            }
42
            if (array_key_exists($name, $params)) {
43
                $args[] = $this->argType($param, $params[$name]);
44
            } elseif ($param->isDefaultValueAvailable()) {
45
                $args[] = $param->getDefaultValue();
46
            } else {
47
                $missing[] = $name;
48
            }
49
        }
50
51
        if (!empty($missing)) {
52
            throw new InvalidArgumentException(sprintf(
53
                'Missing required parameters "%s".',
54
                implode(', ', $missing)
55
            ));
56
        }
57
58
        return $args;
59
    }
60
61
    /**
62
     * @param ReflectionParameter $param
63
     * @param $value
64
     * @return mixed
65
     */
66
    private function argType(
67
        ReflectionParameter $param,
68
        $value
69
    ) {
70
        if (!$param->hasType()) {
71
            return $value;
72
        }
73
74
        if ($param->isArray()) {
75
            return (array)$value;
76
        }
77
78
        if ($param->isCallable() && is_callable($value)) {
79
            return $value;
80
        }
81
82
        if (!is_array($value)) {
83
            return $value;
84
        }
85
86
        throw new InvalidArgumentException(sprintf(
87
            'Invalid data received for parameter "%s".',
88
            $param->name
89
        ));
90
    }
91
}
92