Completed
Pull Request — master (#4)
by Paweł
02:32
created

Mapper::populate()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 10
nc 4
nop 3
1
<?php
2
/**
3
 * Created for IG Client.
4
 * User: jakim <[email protected]>
5
 * Date: 16.03.2018
6
 */
7
8
namespace Jakim\Base;
9
10
11
use Jakim\Helper\ArrayHelper;
12
13
abstract class Mapper
14
{
15
    /**
16
     * Attributes map.
17
     *
18
     * @return array
19
     */
20
    abstract protected function map(): array;
21
22
    public function normalizeData(string $class, array $data)
23
    {
24
        $envelopeKey = ArrayHelper::getValue($this->map(), "$class.envelope");
25
        if ($envelopeKey) {
26
            $data = ArrayHelper::getValue($data, $envelopeKey, []);
27
        }
28
29
        return $data;
30
    }
31
32
    public function populate(string $class, array $data, $relations = false)
33
    {
34
        $itemMap = ArrayHelper::getValue($this->map(), "$class.item", []);
35
36
        $model = new $class();
37
        foreach ($itemMap as $to => $from) {
38
            $model->$to = ArrayHelper::getValue($data, $from);
39
        }
40
41
        $relationsMap = ArrayHelper::getValue($this->map(), "$class.relations");
42
        if ($relations && $relationsMap) {
43
            foreach ($relationsMap as $to => $class) {
44
                $relationData = $this->normalizeData($class, $data);
45
                $model->$to = $this->populate($class, $relationData);
46
            }
47
        }
48
49
        return $model;
50
    }
51
52
}