/
MultiEntityIterator.php
131 lines (102 loc) · 2.31 KB
/
MultiEntityIterator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
<?php declare(strict_types = 1);
namespace Nextras\Orm\Collection;
use Countable;
use Iterator;
use Nette\Utils\Arrays;
use Nextras\Orm\Entity\IEntity;
use Nextras\Orm\Entity\IEntityHasPreloadContainer;
use Nextras\Orm\Exception\InvalidStateException;
/**
* @implements Iterator<int, IEntity>
*/
class MultiEntityIterator implements IEntityPreloadContainer, Iterator, Countable
{
/** @var int */
private $position = 0;
/**
* @var IEntity[][]
* @phpstan-var array<int|string, list<IEntity>>
*/
private $data;
/**
* @var IEntity[]
* @phpstan-var list<IEntity>
*/
private $iterable;
/**
* @var array
* @phpstan-var array<string, list<mixed>>
*/
private $preloadCache;
/**
* @phpstan-param array<int|string, list<IEntity>> $data
*/
public function __construct(array $data)
{
$this->data = $data;
}
/**
* @param mixed $index
*/
public function setDataIndex($index): void
{
if (!isset($this->data[$index])) {
$this->data[$index] = [];
}
$this->iterable = &$this->data[$index];
assert(Arrays::isList($this->iterable));
$this->rewind();
}
public function next(): void
{
++$this->position;
}
public function current(): IEntity
{
if (!isset($this->iterable[$this->position])) {
throw new InvalidStateException();
}
$current = $this->iterable[$this->position];
if ($current instanceof IEntityHasPreloadContainer) {
$current->setPreloadContainer($this);
}
return $current;
}
#[\ReturnTypeWillChange]
public function key()
{
return $this->position;
}
public function valid(): bool
{
return isset($this->iterable[$this->position]);
}
public function rewind(): void
{
$this->position = 0;
}
public function count(): int
{
return count($this->iterable);
}
public function getPreloadValues(string $property): array
{
if (isset($this->preloadCache[$property])) {
return $this->preloadCache[$property];
}
$values = [];
foreach ($this->data as $entities) {
foreach ($entities as $entity) {
// property may not exist when using STI
if ($entity->getMetadata()->hasProperty($property)) {
// relationship may be already nulled in removed entity
$value = $entity->getRawValue($property);
if ($value !== null) {
$values[] = $value;
}
}
}
}
return $this->preloadCache[$property] = $values;
}
}