Completed
Push — master ( dbcf6b...d53ab6 )
by Peter
44:13 queued 37:37
created

ForeignMappingTransformer::getMappedValue()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.0261

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 6
cts 7
cp 0.8571
rs 9.7998
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3.0261
1
<?php
2
3
namespace TreeHouse\IoBundle\Item\Modifier\Data\Transformer;
4
5
use TreeHouse\Feeder\Exception\TransformationFailedException;
6
use TreeHouse\Feeder\Modifier\Data\Transformer\TransformerInterface;
7
8
class ForeignMappingTransformer implements TransformerInterface
9
{
10
    /**
11
     * @var string
12
     */
13
    protected $name;
14
15
    /**
16
     * @var array
17
     */
18
    protected $mapping;
19
20
    /**
21
     * @param string $name
22
     * @param array  $mapping
23
     */
24 8
    public function __construct($name, array $mapping)
25
    {
26 8
        $this->name = $name;
27 8
        $this->mapping = $mapping;
28 8
    }
29
30 8
    public function transform($value)
31
    {
32 8
        if (is_null($value)) {
33 2
            return $value;
34
        }
35
36 6
        if (is_scalar($value)) {
37 4
            return $this->getMappedValue($value);
38
        }
39
40 2
        if (is_array($value)) {
41 2
            $newValue = [];
42
43 2
            foreach ($value as $val) {
44 2
                if (!is_array($val)) {
45 2
                    $val = [$val];
46
                }
47 2
                foreach ($val as $val2) {
48 2
                    $newValue[] = $this->getMappedValue($val2);
49
                }
50
            }
51
52 2
            return array_filter($newValue);
53
        }
54
55
        throw new TransformationFailedException(
56
            sprintf(
57
                'Expected a scalar value or an array of scalar values to transform, got %s instead',
58
                json_encode($value)
59
            )
60
        );
61
    }
62
63
    /**
64
     * @param string $value
65
     *
66
     * @throws TransformationFailedException
67
     *
68
     * @return string
69
     */
70 6
    protected function getMappedValue($value)
71
    {
72 6
        if (null === $value) {
73
            return $value;
74
        }
75
76 6
        if (!array_key_exists($value, $this->mapping)) {
77 2
            throw new TransformationFailedException(
78 2
                sprintf('Value %s not found for key "%s"', json_encode($value), $this->name)
79
            );
80
        }
81
82 4
        return $this->mapping[$value];
83
    }
84
}
85