Passed
Push — master ( 70669e...6100bc )
by Tomasz
01:54
created

ScalarTransformerWalker   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
dl 0
loc 40
ccs 19
cts 19
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A transform() 0 14 3
A walk() 0 11 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 new InvalidArgumentException(sprintf(
45 1
            'Type "%s" is invalid. There is no "%s" function. Fix your type or add that function to global namespace',
46 1
            $type,
47 1
            $function
48
        ));
49
    }
50
}
51