Marshal::getParameterValueForCommand()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 19
ccs 8
cts 8
cp 1
rs 9.2
cc 4
eloc 11
nc 4
nop 3
crap 4
1
<?php
2
3
namespace Mosaic\CommandBus;
4
5
use ArrayAccess;
6
use InvalidArgumentException;
7
use ReflectionClass;
8
use ReflectionParameter;
9
10
class Marshal
11
{
12
    /**
13
     * @param  string      $command
14
     * @param  ArrayAccess $input
15
     * @param  array       $extra
16
     * @return object
17
     */
18 9
    public function getClassInstance($command, ArrayAccess $input, array $extra = [])
19
    {
20 9
        $injected = [];
21
22 9
        $reflection = new ReflectionClass($command);
23
24 9
        if ($constructor = $reflection->getConstructor()) {
25 4
            $injected = array_map(function ($parameter) use ($input, $extra) {
26 4
                return $this->getParameterValueForCommand($input, $parameter, $extra);
27 4
            }, $constructor->getParameters());
28
        }
29
30 8
        return $reflection->newInstanceArgs($injected);
31
    }
32
33
    /**
34
     * Get a parameter value for a marshaled command.
35
     *
36
     * @param ArrayAccess         $source
37
     * @param ReflectionParameter $parameter
38
     * @param array               $extras
39
     *
40
     * @return mixed
41
     */
42 4
    protected function getParameterValueForCommand(
43
        ArrayAccess $source,
44
        ReflectionParameter $parameter,
45
        array $extras = []
46
    ) {
47 4
        if (array_key_exists($parameter->name, $extras)) {
48 1
            return $extras[$parameter->name];
49
        }
50
51 4
        if (isset($source[$parameter->name])) {
52 2
            return $source[$parameter->name];
53
        }
54
55 2
        if ($parameter->isDefaultValueAvailable()) {
56 1
            return $parameter->getDefaultValue();
57
        }
58
59 1
        throw new InvalidArgumentException("Unable to map input to command: {$parameter->name}");
60
    }
61
}
62