Completed
Push — master ( d3ce3a...b1bb73 )
by Valentin
06:29
created

Resolver::getEntityFromSource()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Cycle\ORM\Promise;
5
6
use Cycle\ORM\ORMInterface;
7
use Cycle\ORM\Select;
8
9
final class Resolver implements PromiseInterface
10
{
11
    /** @var ORMInterface */
12
    private $orm;
13
14
    /** @var string */
15
    private $role;
16
17
    /** @var array */
18
    private $scope;
19
20
    /** @var bool */
21
    private $loaded = false;
22
23
    /** @var PromiseInterface|null */
24
    private $entity;
25
26
    /**
27
     * @param ORMInterface $orm
28
     * @param string       $role
29
     * @param array        $scope
30
     */
31
    public function __construct(ORMInterface $orm, string $role, array $scope)
32
    {
33
        $this->orm = $orm;
34
        $this->role = $role;
35
        $this->scope = $scope;
36
    }
37
38
    public function __clone()
39
    {
40
        if ($this->entity !== null) {
41
            $this->entity = clone $this->entity;
42
        }
43
    }
44
45
    /**
46
     * @inheritdoc
47
     */
48
    public function __loaded(): bool
49
    {
50
        return $this->loaded;
51
    }
52
53
    /**
54
     * @inheritdoc
55
     */
56
    public function __role(): string
57
    {
58
        return $this->role;
59
    }
60
61
    /**
62
     * @inheritdoc
63
     */
64
    public function __scope(): array
65
    {
66
        return $this->scope;
67
    }
68
69
    /**
70
     * @inheritdoc
71
     */
72
    public function __resolve()
73
    {
74
        if (!$this->loaded) {
75
            $this->loaded = true;
76
77
            // use entity from heap, if has already been loaded in memory otherwise select from repository
78
            $this->entity = $this->getEntityFromHeap() ?? $this->getEntityFromSource();
79
        }
80
81
        return $this->entity;
82
    }
83
84
    /**
85
     * @return object|null
86
     */
87
    private function getEntityFromHeap()
88
    {
89
        if (empty($this->scope)) {
90
            return null;
91
        }
92
93
        $key = key($this->scope);
94
        $value = $this->scope[$key];
95
96
        return $this->orm->getHeap()->find($this->role, $key, $value);
97
    }
98
99
    /**
100
     * @return object|null
101
     */
102
    private function getEntityFromSource()
103
    {
104
        return $this->orm->getRepository($this->role)->findOne($this->scope);
105
    }
106
}