Passed
Pull Request — master (#188)
by
unknown
02:35
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
    /**
22
     * @var ORMInterface
23
     */
24
    private $orm;
25
26
    /**
27
     * @var string
28
     */
29
    private $role;
30
31
    /**
32
     * @var iterable
33
     */
34
    private $source;
35
36
    /**
37
     * @var bool
38
     */
39
    private $tryToFindInHeap;
40
41
    /**
42
     * @param ORMInterface $orm
43
     * @param string $class
44
     * @param iterable $source
45
     * @param bool $tryToFindInHeap
46
     */
47
    public function __construct(ORMInterface $orm, string $class, iterable $source, bool $tryToFindInHeap = false)
48
    {
49
        $this->orm = $orm;
50
        $this->role = $this->orm->resolveRole($class);
51
        $this->source = $source;
52
        $this->tryToFindInHeap = $tryToFindInHeap;
53
    }
54
55
    /**
56
     * Generate entities using incoming data stream. Pivoted data would be
57
     * returned as key value if set.
58
     *
59
     * @return \Generator
60
     */
61
    public function getIterator(): \Generator
62
    {
63
        foreach ($this->source as $index => $data) {
64
            // through-like relations
65
            if (isset($data['@'])) {
66
                $index = $data;
67
                unset($index['@']);
68
                $data = $data['@'];
69
            }
70
71
            // add pipeline filter support?
72
73
            yield $index => $this->getEntity($data);
74
        }
75
    }
76
77
    private function getEntity(array $data)
78
    {
79
        if ($this->tryToFindInHeap) {
80
            $pk = $this->orm->getSchema()->define($this->role, SchemaInterface::PRIMARY_KEY);
81
            $id = $data[$pk] ?? null;
82
83
            if (null !== $id) {
84
                $e = $this->orm->getHeap()->find($this->role, [
85
                    $pk => $id,
86
                ]);
87
            }
88
        }
89
90
        return $e ?? $this->orm->make($this->role, $data, Node::MANAGED);
91
    }
92
}
93