EntityMapper::createEntityInstance()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 2
nop 1
1
<?php
2
declare(strict_types = 1);
3
namespace Agares\MicroORM;
4
5
use Agares\MicroORM\TypeMappers\IntegerTypeMapper;
6
use Agares\MicroORM\TypeMappers\StringTypeMapper;
7
8
final class EntityMapper implements EntityMapperInterface
9
{
10
    /** @var TypeMapperInterface[] */
11
    private $typeMappers = array();
12
13
    public function __construct(array $typeMappers = null)
14
    {
15
        if ($typeMappers == null) {
16
            $typeMappers = [
17
                'string' => new StringTypeMapper(),
18
                'int' => new IntegerTypeMapper()
19
            ];
20
        }
21
22
        $this->typeMappers = $typeMappers;
23
    }
24
25
    public function map(array $fields, EntityDefinition $entityDefinition)
26
    {
27
        $entityReflection = new \ReflectionClass($entityDefinition->getClassName());
28
29
        $instance = $this->createEntityInstance($entityReflection);
30
        $this->mapEntityFields($fields, $entityReflection, $instance, $entityDefinition->getFields());
31
32
        return $instance;
33
    }
34
35
    private function createEntityInstance(\ReflectionClass $entityReflection)
36
    {
37
        $constructorReflection = $entityReflection->getConstructor();
38
39
        if ($constructorReflection === null || count($constructorReflection->getParameters()) === 0) {
40
            $instance = $entityReflection->newInstance();
41
        } else {
42
            $instance = $entityReflection->newInstanceWithoutConstructor();
43
        }
44
45
        return $instance;
46
    }
47
48
    /**
49
     * @param array $fields
50
     * @param \ReflectionClass $entityReflection
51
     * @param mixed $entityInstance
52
     * @param EntityFieldDefinition[] $fieldsDefinition
53
     *
54
     * @throws UnknownFieldTypeException
55
     */
56
    private function mapEntityFields(array $fields, \ReflectionClass $entityReflection, $entityInstance, array $fieldsDefinition)
57
    {
58
        foreach ($fieldsDefinition as $fieldName => $definition) {
59
            $typeName = $definition->getTypeName();
60
61
            if (!isset($this->typeMappers[$typeName])) {
62
                throw new UnknownFieldTypeException($typeName);
63
            }
64
65
            $fieldReflection = $entityReflection->getProperty($definition->getFieldName());
66
            $fieldReflection->setAccessible(true);
67
            $fieldReflection->setValue($entityInstance, $this->typeMappers[$typeName]->fromString($fieldName, $fields));
68
            $fieldReflection->setAccessible(false);
69
        }
70
    }
71
}