RecordInstantiator   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 2
dl 0
loc 65
rs 10
c 0
b 0
f 0

2 Methods

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