Passed
Push — master ( 0057b2...3e8fcf )
by Marek
02:11
created

ArrayMapper::map()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5.0342

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 8
cts 9
cp 0.8889
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 10
nc 3
nop 2
crap 5.0342
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace AppBuilder\Application\Utils\Mapper;
6
7
use AppBuilder\Application\Module\Jira\Exception\MapperRepetitionException;
8
9
class ArrayMapper implements Mapper
10
{
11
    /** @var string */
12
    private $key;
13
14
    /** @var string */
15
    private $outputKey;
16
17
    /** @var array */
18
    private $mappers = [];
19
20 2
    public function __construct(string $key, array $fieldMappers, string $outputKey = '')
21
    {
22 2
        $this->key       = $key;
23 2
        $this->outputKey = $outputKey;
24
25 2
        if ('' === $outputKey) {
26 2
            $this->outputKey = $key;
27
        }
28 2
        foreach ($fieldMappers as $mapper) {
29 2
            if (array_key_exists($mapper->key(), $this->mappers)) {
30 1
                throw new MapperRepetitionException('Mapper with key: ' . $mapper->key() . ' already exists');
31
            }
32 2
            $this->mappers[$mapper->key()] = $mapper;
33
        }
34 2
    }
35
36 2
    public function key() : string
37
    {
38 2
        return $this->key;
39
    }
40
41
    /** Returns outputKey passed in constructor. If not passed, returns key value */
42 1
    public function outputKey() : string
43
    {
44 1
        return $this->outputKey;
45
    }
46
47
    /**
48
     * Returns associative array with passed mappers.
49
     */
50 1
    public function map(array $passedData, array $context = [])
51
    {
52 1
        $data   = $passedData[$this->key];
53 1
        $result = [];
54 1
        foreach ($this->mappers as $mapper) {
55 1
            $this->outputKey = $mapper->outputKey();
56 1
            if (null === $data || !array_key_exists($mapper->key(), $data)) {
57
                $result = null;
58
            } else {
59 1
                $result = $mapper->map($data, $context ?: $data);
60
            }
61
        }
62
63 1
        return $result;
64
    }
65
}
66