Passed
Push — master ( 33c6fc...b4603e )
by Adrian
01:36
created

GenericEntityHydrator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Importance

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

6 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
A get() 0 3 1
A set() 0 3 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
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
    public function get($entity, $attribute)
55
    {
56
        return $entity->{$attribute};
57
    }
58
59
    public function set($entity, $attribute, $value)
60
    {
61
        return $entity->{$attribute} = $value;
62
    }
63
}
64