Completed
Push — master ( a7b476...58257b )
by Adrian
01:51
created

GenericEntityHydrator::mapAttributesToColumns()   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->orm
31
            ->getCastingManager()
32
            ->castArray($attributes, $this->mapper->getCasts());
33
        $attributes = Arr::renameKeys($attributes, $this->mapper->getColumnAttributeMap());
34
        $class      = $this->mapper->getEntityClass() ?? GenericEntity::class;
35
36
        return new $class($attributes, $this->orm->getCastingManager());
37
    }
38
39
    public function extract(EntityInterface $entity)
40
    {
41
        $data = Arr::renameKeys(
42
            $entity->getArrayCopy(),
43
            array_flip($this->mapper->getColumnAttributeMap())
44
        );
45
        $data = $this->orm
46
            ->getCastingManager()
47
            ->castArrayForDb($data, $this->mapper->getCasts());
48
49
        return Arr::only($data, $this->mapper->getColumns());
50
    }
51
}
52