Completed
Push — master ( e55059...ea0818 )
by Adrian
02:34
created

GenericEntityHydrator   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 16
c 1
b 0
f 1
dl 0
loc 42
rs 10
wmc 4

4 Methods

Rating   Name   Duplication   Size   Complexity  
A setMapper() 0 3 1
A extract() 0 10 1
A setCastingManager() 0 3 1
A hydrate() 0 8 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Sirius\Orm\Entity;
5
6
use Sirius\Orm\CastingManager;
7
use Sirius\Orm\Helpers\Arr;
8
use Sirius\Orm\Mapper;
9
10
class GenericEntityHydrator implements HydratorInterface
11
{
12
    /**
13
     * @var $castingManager
0 ignored issues
show
Documentation Bug introduced by
The doc comment $castingManager at position 0 could not be parsed: Unknown type name '$castingManager' at position 0 in $castingManager.
Loading history...
14
     */
15
    protected $castingManager;
16
17
    /**
18
     * @var Mapper
19
     */
20
    protected $mapper;
21
22
    public function setMapper(Mapper $mapper)
23
    {
24
        $this->mapper = $mapper;
25
    }
26
27
    public function setCastingManager(CastingManager $castingManager)
28
    {
29
        $this->castingManager = $castingManager;
30
    }
31
32
    public function hydrate(array $attributes = [])
33
    {
34
        $attributes = $this->castingManager
35
                           ->castArray($attributes, $this->mapper->getCasts());
36
        $attributes = Arr::renameKeys($attributes, $this->mapper->getColumnAttributeMap());
37
        $class      = $this->mapper->getEntityClass() ?? GenericEntity::class;
38
39
        return new $class($attributes, $this->castingManager);
40
    }
41
42
    public function extract(EntityInterface $entity)
43
    {
44
        $data = Arr::renameKeys(
45
            $entity->getArrayCopy(),
46
            array_flip($this->mapper->getColumnAttributeMap())
47
        );
48
        $data = $this->castingManager
49
                     ->castArrayForDb($data, $this->mapper->getCasts());
50
51
        return Arr::only($data, $this->mapper->getColumns());
52
    }
53
}
54