Passed
Push — master ( 82a58b...d35cf8 )
by Tomasz
02:32
created

ScalarTransformerWalker::transform()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 2
nop 2
crap 3
1
<?php
2
declare(strict_types=1);
3
4
namespace ReadModel\Walker;
5
6
use ReadModel\InvalidArgumentException;
7
8
class ScalarTransformerWalker implements ResultWalker
9
{
10
    /** @var array */
11
    private $typeMapping;
12
13
    /**
14
     * @param array $typeMapping e.g: ['id' => 'int', 'active' => 'bool']
15
     */
16 5
    public function __construct(array $typeMapping)
17
    {
18 5
        $this->typeMapping = $typeMapping;
19 5
    }
20
21
    public function walk(array $result): array
22
    {
23 3
        array_walk($result, function (&$value, $key) {
24 3
            if ($value === null || !isset($this->typeMapping[$key])) {
25 1
                return;
26
            }
27
28 2
            $value = $this->transform($value, $this->typeMapping[$key]);
29 3
        });
30
31 2
        return $result;
32
    }
33
34 2
    private function transform($value, $type)
35
    {
36 2
        $type = strtolower($type);
37 2
        $type = 'boolean' === $type ? 'bool' : $type;
38 2
        $function = $type.'val';
39
40 2
        if (function_exists($function)) {
41 1
            return $function($value);
42
        }
43
44 1
        throw InvalidArgumentException::invalidType($type, $function);
45
    }
46
}
47