LazyLoad::overrideLazyProperty()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 2
dl 0
loc 9
ccs 0
cts 7
cp 0
crap 6
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
namespace vakata\orm;
4
5
trait LazyLoad
6
{
7
    protected $lazyProperties = [];
8 6
    public function lazyProperty(string $property, callable $resolve)
9
    {
10 6
        unset($this->{$property});
11 6
        $this->lazyProperties[$property] = [ 'loaded' => false, 'value' => null, 'resolve' => $resolve ];
12 6
        return $this;
13
    }
14
    public function overrideLazyProperty(string $property, $value)
15
    {
16
        if (!isset($this->lazyProperties[$property])) {
17
            return $this;
18
        }
19
        $this->lazyProperties[$property]['value'] = $value;
20
        $this->lazyProperties[$property]['loaded'] = true;
21
        $this->{$property} = $this->lazyProperties[$property]['value'];
22
        return $this;
23
    }
24 2
    public function loadLazyProperty(string $property)
25
    {
26 2
        if (!isset($this->lazyProperties[$property])) {
27
            throw new \Exception('Lazy property not found');
28
        }
29 2
        if ($this->lazyProperties[$property]['loaded']) {
30
            return $this->lazyProperties[$property]['value'];
31
        }
32 2
        $this->lazyProperties[$property]['value'] = call_user_func($this->lazyProperties[$property]['resolve']);
33 2
        $this->lazyProperties[$property]['loaded'] = true;
34 2
        return $this->{$property} = $this->lazyProperties[$property]['value'];
35
    }
36 2
    public function __get($property)
37
    {
38 2
        if (isset($this->lazyProperties[$property])) {
39 2
            return $this->loadLazyProperty($property);
40
        }
41
        return null;
42
    }
43
}