Completed
Branch feature/pre-split (9d6b17)
by Anton
03:28
created

RecordInstantiator::identify()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 12
nop 1
dl 0
loc 20
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/**
3
 * components
4
 *
5
 * @author    Wolfy-J
6
 */
7
namespace Spiral\ORM\Entities;
8
9
use Spiral\ORM\Exceptions\InstantionException;
10
use Spiral\ORM\InstantiatorInterface;
11
use Spiral\ORM\ORMInterface;
12
use Spiral\ORM\RecordInterface;
13
14
/**
15
 * Default instantiator for records.
16
 */
17
class RecordInstantiator implements InstantiatorInterface
18
{
19
    /**
20
     * @invisible
21
     * @var ORMInterface
22
     */
23
    private $orm;
24
25
    /**
26
     * Record class.
27
     *
28
     * @var string
29
     */
30
    private $class = '';
31
32
    /**
33
     * @param ORMInterface $orm
34
     * @param string       $class
35
     */
36
    public function __construct(ORMInterface $orm, string $class)
37
    {
38
        $this->orm = $orm;
39
        $this->class = $class;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     *
45
     * @return RecordInterface
46
     *
47
     * @throws InstantionException
48
     */
49
    public function make($fields, int $state): RecordInterface
50
    {
51
        if (!is_array($fields)) {
52
            $fields = iterator_to_array($fields);
53
        }
54
55
        $class = $this->class;
56
57
        //Now we can construct needed class, in this case we are following DocumentEntity declaration
58
        if ($state == ORMInterface::STATE_LOADED) {
59
            //No need to filter values, passing directly in constructor
60
            return new $class($fields, $state, $this->orm);
61
        }
62
63
        if ($state != ORMInterface::STATE_NEW) {
64
            throw new InstantionException(
65
                "Undefined state {$state}, only NEW and LOADED are supported"
66
            );
67
        }
68
69
        /*
70
         * Filtering entity
71
         */
72
73
        $entity = new $class([], $state, $this->orm);
74
        if (!$entity instanceof RecordInterface) {
75
            throw new InstantionException(
76
                "Unable to set filtered values for '{$class}', must be instance of RecordInterface"
77
            );
78
        }
79
80
        //Must pass value thought all needed filters
81
        $entity->setFields($fields);
82
83
        return $entity;
84
    }
85
86
}
87