Completed
Pull Request — master (#2)
by René
05:02 queued 02:37
created

EntityFactory::createFromArray()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 32
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 32
ccs 15
cts 15
cp 1
rs 8.8571
c 0
b 0
f 0
cc 2
eloc 15
nc 2
nop 1
crap 2
1
<?php
2
declare(strict_types = 1);
3
4
namespace Zortje\MVC\Model\Table\Entity;
5
6
/**
7
 * Class EntityFactory
8
 *
9
 * @package Zortje\MVC\Model\Table\Entity
10
 */
11
class EntityFactory
12
{
13
14
    /**
15
     * @var String Entity class
16
     */
17
    protected $entityClass;
18
19
    /**
20
     * @param string $entityClass
21
     */
22 1
    public function __construct(string $entityClass)
23
    {
24 1
        $this->entityClass = $entityClass;
25 1
    }
26
27
    /**
28
     * @param array $array
29
     *
30
     * @return Entity
31
     */
32 1
    public function createFromArray(array $array): Entity
33
    {
34
        /**
35
         * @var Entity $entity
36
         */
37 1
        $reflector = new \ReflectionClass($this->entityClass);
38
39 1
        $entity = $reflector->newInstanceWithoutConstructor();
40
41 1
        $columns = $entity::getColumns();
42 1
        unset($columns['uuid'], $columns['modified'], $columns['created']);
43
44 1
        $arguments = [];
45
46 1
        foreach ($columns as $column => $type) {
47 1
            $property = new EntityProperty($type);
48
49 1
            $arguments[$column] = $property->formatValueForEntity($array[$column]);
50
        }
51
52 1
        $entity = $reflector->newInstanceArgs($arguments);
53 1
        $entity->set('uuid', $array['uuid']);
54 1
        $entity->set('modified', new \DateTime($array['modified']));
55 1
        $entity->set('created', new \DateTime($array['created']));
56
57
        /**
58
         * Mark entity as unaltered
59
         */
60 1
        $entity->setUnaltered();
61
62 1
        return $entity;
63
    }
64
}
65