MapperTrait::setMap()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 5
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
/**
4
 * @author    Flipbox Factory
5
 * @copyright Copyright (c) 2017, Flipbox Digital
6
 * @link      https://github.com/flipbox/transform/releases/latest
7
 * @license   https://github.com/flipbox/transform/blob/master/LICENSE
8
 */
9
10
namespace Flipbox\Transform\Traits;
11
12
use Flipbox\Transform\Helpers\MapperHelper;
13
14
/**
15
 * @author Flipbox Factory <[email protected]>
16
 * @since 3.0.0
17
 */
18
trait MapperTrait
19
{
20
    /**
21
     * @var array
22
     */
23
    private $map;
24
25
    /**
26
     * @param $map
27
     * @return $this
28
     */
29
    public function setMap($map)
30
    {
31
        $this->map = $map;
32
        return $this;
33
    }
34
35
    /**
36
     * @param array $array
37
     * @return array
38
     */
39
    protected function definedMap(array $array): array
40
    {
41
        return [];
42
    }
43
44
    /**
45
     * @param array $array
46
     * @return array
47
     */
48
    public function getMap(array $array): array
49
    {
50
        if (!$this->hasMap()) {
51
            $this->map = $this->definedMap($array);
52
        }
53
        return $this->resolveMap($this->map);
54
    }
55
56
    /**
57
     * @return bool
58
     */
59
    public function hasMap(): bool
60
    {
61
        return $this->map !== null;
62
    }
63
64
    /**
65
     * @param $map
66
     * @return array
67
     */
68
    protected function resolveMap($map): array
69
    {
70
        if (is_array($map)) {
71
            return $map;
72
        }
73
74
        if (is_callable($map)) {
75
            return $this->resolveMap(call_user_func($map));
76
        }
77
78
        return [$map];
79
    }
80
81
    /**
82
     * @param array $array
83
     * @return array
84
     */
85
    public function mapTo(array $array): array
86
    {
87
        return MapperHelper::to($array, $this->getMap($array));
88
    }
89
90
    /**
91
     * @param array $array
92
     * @return array
93
     */
94
    public function mapFrom(array $array): array
95
    {
96
        return MapperHelper::from($array, $this->getMap($array));
97
    }
98
}
99