Passed
Push — master ( 1d083d...fc7ead )
by Anton
04:06
created

Iterator::getEntity()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 3
nop 1
dl 0
loc 14
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Cycle DataMapper ORM
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Cycle\ORM;
13
14
use Cycle\ORM\Heap\Node;
15
16
/**
17
 * Iterates over given data-set and instantiates objects.
18
 */
19
final class Iterator implements \IteratorAggregate
20
{
21
    /** @var ORMInterface */
22
    private $orm;
23
24
    /** @var string */
25
    private $role;
26
27
    /** @var iterable */
28
    private $source;
29
30
    /** @var bool */
31
    private $tryToFindInHeap;
32
33
    /**
34
     * @param ORMInterface $orm
35
     * @param string $class
36
     * @param iterable $source
37
     * @param bool $tryToFindInHeap
38
     */
39
    public function __construct(ORMInterface $orm, string $class, iterable $source, bool $tryToFindInHeap = false)
40
    {
41
        $this->orm = $orm;
42
        $this->role = $this->orm->resolveRole($class);
43
        $this->source = $source;
44
        $this->tryToFindInHeap = $tryToFindInHeap;
45
    }
46
47
    /**
48
     * Generate entities using incoming data stream. Pivoted data would be
49
     * returned as key value if set.
50
     *
51
     * @return \Generator
52
     */
53
    public function getIterator(): \Generator
54
    {
55
        foreach ($this->source as $index => $data) {
56
            // through-like relations
57
            if (isset($data['@'])) {
58
                $index = $data;
59
                unset($index['@']);
60
                $data = $data['@'];
61
            }
62
63
            // add pipeline filter support?
64
65
            yield $index => $this->getEntity($data);
66
        }
67
    }
68
69
    private function getEntity(array $data)
70
    {
71
        if ($this->tryToFindInHeap) {
72
            $pk = $this->orm->getSchema()->define($this->role, SchemaInterface::PRIMARY_KEY);
73
            $id = $data[$pk] ?? null;
74
75
            if (null !== $id) {
76
                $e = $this->orm->getHeap()->find($this->role, [
77
                    $pk => $id,
78
                ]);
79
            }
80
        }
81
82
        return $e ?? $this->orm->make($this->role, $data, Node::MANAGED);
83
    }
84
}
85