LazyPropertiesTrait   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 8
c 0
b 0
f 0
lcom 1
cbo 1
dl 0
loc 57
ccs 0
cts 25
cp 0
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A registerLoader() 0 8 2
A registerLoaders() 0 6 2
A load() 0 14 4
1
<?php
2
3
namespace Majora\Framework\Model;
4
5
/**
6
 * Trait which provides lazy load delegates call on fields.
7
 */
8
trait LazyPropertiesTrait
9
{
10
    /**
11
     * @var EntityCollection
12
     */
13
    private $delegatesCollection;
14
15
    /**
16
     * @see LazyPropertiesInterface::registerLoader()
17
     */
18
    public function registerLoader($field, \Closure $delegate)
19
    {
20
        if (!$this->delegatesCollection instanceof EntityCollection) {
21
            $this->delegatesCollection = new EntityCollection();
22
        }
23
24
        $this->delegatesCollection->set(strtolower($field), $delegate);
25
    }
26
27
    /**
28
     * @see LazyPropertiesInterface::registerLoaders()
29
     */
30
    public function registerLoaders(array $loaders)
31
    {
32
        foreach ($loaders as $field => $closure) {
33
            $this->registerLoader($field, $closure);
34
        }
35
    }
36
37
    /**
38
     * Load given field if able to, define his value and return it.
39
     *
40
     * @example
41
     *   public function getRelatedEntity()
42
     *   {
43
     *       return $this->load('relatedEntity');
44
     *   }
45
     *
46
     * @param string $field
47
     *
48
     * @return mixed|null field value if retrieved
49
     */
50
    protected function load($field)
51
    {
52
        if (!is_null($this->$field)
53
            || !$this->delegatesCollection
54
            || !$this->delegatesCollection->containsKey($key = strtolower($field))
55
        ) {
56
            return $this->$field;
57
        }
58
59
        $loader = $this->delegatesCollection->get($key);
60
        $this->delegatesCollection->remove($key);
61
62
        return $this->$field = $loader($this);
63
    }
64
}
65