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

ScalarTransformerWalker::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 1
crap 1
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