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

GenericEntityHydrator::setCastingManager()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
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