Completed
Push — master ( eacc73...69d932 )
by Adrian
01:58
created

GenericEntityHydrator::mapColumnsToAttributes()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 4
eloc 8
c 1
b 0
f 1
nc 4
nop 1
dl 0
loc 15
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace Sirius\Orm\Entity;
5
6
use Sirius\Orm\Helpers\Arr;
7
use Sirius\Orm\Mapper;
8
use Sirius\Orm\Orm;
9
10
class GenericEntityHydrator implements HydratorInterface
11
{
12
    /**
13
     * @var Orm
14
     */
15
    protected $orm;
16
17
    /**
18
     * @var Mapper
19
     */
20
    protected $mapper;
21
22
    public function __construct(Orm $orm, Mapper $mapper)
23
    {
24
        $this->orm    = $orm;
25
        $this->mapper = $mapper;
26
    }
27
28
    public function hydrate($attributes = [])
29
    {
30
        $attributes = $this->mapColumnsToAttributes($attributes);
31
        $class      = $this->mapper->getEntityClass() ?? GenericEntity::class;
32
33
        return new $class($attributes, $this->orm->getCastingManager());
34
    }
35
36
    protected function mapColumnsToAttributes($arr)
37
    {
38
        $map = $this->mapper->getColumnAttributeMap();
39
        if (empty($map)) {
40
            return $arr;
41
        }
42
43
        foreach ($map as $column => $attribute) {
44
            if (isset($arr[$column])) {
45
                $arr[$attribute] = $arr[$column];
46
                unset($arr[$column]);
47
            }
48
        }
49
50
        return $arr;
51
    }
52
53
    public function extract(EntityInterface $entity)
54
    {
55
        $data = $this->mapAttributesToColumns($entity->getArrayCopy());
56
57
        return Arr::only($data, $this->mapper->getColumns());
58
    }
59
60
    public function mapAttributesToColumns($arr)
61
    {
62
        $map = $this->mapper->getColumnAttributeMap();
63
        if (empty($map)) {
64
            return $arr;
65
        }
66
67
        foreach ($map as $column => $attribute) {
68
            if (isset($arr[$attribute])) {
69
                $arr[$column] = $arr[$attribute];
70
                unset($arr[$attribute]);
71
            }
72
        }
73
74
        return $arr;
75
    }
76
}
77