Resolver::getEntityFromSource()   A
last analyzed

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