Passed
Push — master ( d3a94c...76e109 )
by Valentin
05:50
created

PromiseResolver   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 96
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 5
dl 0
loc 96
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A __loaded() 0 4 1
A __role() 0 4 1
A __scope() 0 4 1
A __resolve() 0 11 2
A getEntityFromHeap() 0 7 1
A getEntityFromSource() 0 8 1
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
class PromiseResolver implements PromiseInterface
10
{
11
    /** @var ORMInterface */
12
    private $orm;
13
14
    /** @var string */
15
    private $target;
16
17
    /** @var array */
18
    private $scope;
19
20
    /** @var bool */
21
    private $loaded;
22
23
    /** @var PromiseInterface|null */
24
    private $entity;
25
26
    /**
27
     * @param ORMInterface $orm
28
     * @param string       $target
29
     * @param array        $scope
30
     */
31
    public function __construct(ORMInterface $orm, string $target, array $scope)
32
    {
33
        $this->orm = $orm;
34
        $this->target = $target;
35
        $this->scope = $scope;
36
    }
37
38
    /**
39
     * @inheritdoc
40
     */
41
    public function __loaded(): bool
42
    {
43
        return $this->loaded;
44
    }
45
46
    /**
47
     * @inheritdoc
48
     */
49
    public function __role(): string
50
    {
51
        return $this->target;
52
    }
53
54
    /**
55
     * @inheritdoc
56
     */
57
    public function __scope(): array
58
    {
59
        return $this->scope;
60
    }
61
62
    /**
63
     * @inheritdoc
64
     */
65
    public function __resolve()
66
    {
67
        if (!$this->loaded) {
68
            $this->loaded = true;
69
70
            // use entity from heap, if has already been loaded in memory otherwise select from repository
71
            $this->entity = $this->getEntityFromHeap() ?? $this->getEntityFromSource();
72
        }
73
74
        return $this->entity;
75
    }
76
77
    /**
78
     * @return object|null
79
     */
80
    private function getEntityFromHeap()
81
    {
82
        $key = key($this->scope);
83
        $value = $this->scope[$key];
84
85
        return $this->orm->getHeap()->find($this->target, $key, $value);
86
    }
87
88
    /**
89
     * @return object|null
90
     */
91
    private function getEntityFromSource()
92
    {
93
        $select = new Select($this->orm, $this->target);
94
95
        return $select->constrain(
96
            $this->orm->getSource($this->target)->getConstrain()
97
        )->fetchOne($this->scope);
98
    }
99
}