1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* components |
4
|
|
|
* |
5
|
|
|
* @author Wolfy-J |
6
|
|
|
*/ |
7
|
|
|
namespace Spiral\ORM\Entities; |
8
|
|
|
|
9
|
|
|
use Spiral\Models\ActiveEntityInterface; |
10
|
|
|
use Spiral\ORM\Exceptions\InstantionException; |
11
|
|
|
use Spiral\ORM\InstantiatorInterface; |
12
|
|
|
use Spiral\ORM\ORMInterface; |
13
|
|
|
use Spiral\ORM\Record; |
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
|
|
|
* Normalized schema delivered by RecordSchema. |
35
|
|
|
* |
36
|
|
|
* @var array |
37
|
|
|
*/ |
38
|
|
|
private $schema = []; |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param ORMInterface $orm |
42
|
|
|
* @param string $class |
43
|
|
|
* @param array $schema |
44
|
|
|
*/ |
45
|
|
|
public function __construct(ORMInterface $orm, string $class, array $schema) |
46
|
|
|
{ |
47
|
|
|
$this->orm = $orm; |
48
|
|
|
$this->class = $class; |
49
|
|
|
$this->schema = $schema; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* {@inheritdoc} |
54
|
|
|
* |
55
|
|
|
* @return ActiveEntityInterface |
56
|
|
|
* |
57
|
|
|
* @throws InstantionException |
58
|
|
|
*/ |
59
|
|
|
public function make($fields, bool $filter = true): ActiveEntityInterface |
60
|
|
|
{ |
61
|
|
|
if (!is_array($fields)) { |
62
|
|
|
$fields = iterator_to_array($fields); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
$class = $this->class; |
66
|
|
|
|
67
|
|
|
//Now we can construct needed class, in this case we are following DocumentEntity declaration |
68
|
|
|
if (!$filter) { |
69
|
|
|
//No need to filter values, passing directly in constructor |
70
|
|
|
return new $class($fields, $this->schema, $this->orm); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/* |
74
|
|
|
* Filtering entity |
75
|
|
|
*/ |
76
|
|
|
|
77
|
|
|
$entity = new $class($fields, $this->schema, $this->orm); |
78
|
|
|
if (!$entity instanceof Record) { |
79
|
|
|
throw new InstantionException( |
80
|
|
|
"Unable to set filtered values for '{$class}', must be instance of Record" |
81
|
|
|
); |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
//Must pass value thought all needed filters |
85
|
|
|
$entity->stateValue($fields); |
86
|
|
|
|
87
|
|
|
return $entity; |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
} |