Completed
Branch feature/pre-split (2ed6c7)
by Anton
04:25
created

RecordIterator::getIterator()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 2
nop 0
dl 0
loc 18
rs 9.4285
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\Models\EntityInterface;
10
use Spiral\ORM\ORMInterface;
11
12
/**
13
 * Instantiates array of entities. At this moment implementation is rather simple.
14
 *
15
 * @todo upgrade to \IteratorIterator?
16
 */
17
class RecordIterator implements \IteratorAggregate
18
{
19
    /**
20
     * Array of entity data to be fed into instantiators.
21
     *
22
     * @var array
23
     */
24
    private $data = [];
25
26
    /**
27
     * @var EntityInterface[]
28
     */
29
    private $entities = [];
30
31
    /**
32
     * Class to be instantiated.
33
     *
34
     * @var string
35
     */
36
    private $class;
37
38
    /**
39
     * Responsible for entity construction.
40
     *
41
     * @invisible
42
     * @var ORMInterface
43
     */
44
    private $orm;
45
46
    /**
47
     * @param array        $data
48
     * @param string       $class
49
     * @param ORMInterface $orm
50
     */
51
    public function __construct(array $data, string $class, ORMInterface $orm)
52
    {
53
        $this->data = $data;
54
        $this->class = $class;
55
        $this->orm = $orm;
56
    }
57
58
    /**
59
     * @return \ArrayIterator
60
     */
61
    public function getIterator()
62
    {
63
        if (empty($this->entities)) {
64
            foreach ($this->data as $data) {
65
                /*
66
                 * Mass entity initialization.
67
                 */
68
                $this->entities[] = $this->orm->make(
69
                    $this->class,
70
                    $data,
71
                    ORMInterface::STATE_LOADED,
72
                    true
73
                );
74
            }
75
        }
76
77
        return new \ArrayIterator($this->entities);
78
    }
79
}