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

GenericEntityHydrator   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 18
c 1
b 0
f 1
dl 0
loc 40
rs 10
wmc 3

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A extract() 0 11 1
A hydrate() 0 9 1
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