LazyLoad   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Test Coverage

Coverage 56.52%

Importance

Changes 0
Metric Value
dl 0
loc 37
ccs 13
cts 23
cp 0.5652
rs 10
c 0
b 0
f 0
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A loadLazyProperty() 0 11 3
A lazyProperty() 0 5 1
A overrideLazyProperty() 0 9 2
A __get() 0 6 2
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
}