MappingStep::process()   B
last analyzed

Complexity

Conditions 7
Paths 11

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 8.6026
c 0
b 0
f 0
ccs 14
cts 14
cp 1
cc 7
nc 11
nop 2
crap 7
1
<?php
2
3
namespace Port\Steps\Step;
4
5
use Port\Exception\MappingException;
6
use Port\Steps\Step;
7
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
8
use Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException;
9
use Symfony\Component\PropertyAccess\PropertyAccessor;
10
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
11
12
/**
13
 * @author Markus Bachmann <[email protected]>
14
 */
15
class MappingStep implements Step
16
{
17
    /**
18
     * @var array
19
     */
20
    private $mappings = [];
21
22
    /**
23
     * @var PropertyAccessorInterface
24
     */
25
    private $accessor;
26
27
    /**
28
     * @param array                     $mappings
29
     * @param PropertyAccessorInterface $accessor
30
     */
31 5
    public function __construct(array $mappings = [], PropertyAccessorInterface $accessor = null)
32
    {
33 5
        $this->mappings = $mappings;
34 5
        $this->accessor = $accessor ?: new PropertyAccessor();
35 5
    }
36
37
    /**
38
     * @param string $from
39
     * @param string $to
40
     *
41
     * @return $this
42
     */
43 3
    public function map($from, $to)
44
    {
45 3
        $this->mappings[$from] = $to;
46
47 3
        return $this;
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     *
53
     * @throws MappingException
54
     */
55 3
    public function process($item, callable $next)
56
    {
57
        try {
58 3
            foreach ($this->mappings as $from => $to) {
59 3
                $value = $this->accessor->getValue($item, $from);
60 1
                $this->accessor->setValue($item, $to, $value);
61
62 1
                $from = str_replace(['[',']'], '', $from);
63
64
                // Check if $item is an array, because properties can't be unset.
65
                // So we don't call unset for objects to prevent side affects.
66
                // Also, we don't have to unset the property if the key is the same
67 1
                if (is_array($item) && array_key_exists($from, $item) && $from !== str_replace(['[',']'], '', $to)) {
68 1
                    unset($item[$from]);
69 1
                }
70 1
            }
71 3
        } catch (NoSuchPropertyException $exception) {
72 1
            throw new MappingException('Unable to map item', null, $exception);
73 1
        } catch (UnexpectedTypeException $exception) {
74 1
            throw new MappingException('Unable to map item', null, $exception);
75
        }
76
77 1
        return $next($item);
78
    }
79
}
80