LazyPropertiesTrait::registerLoader()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
ccs 0
cts 7
cp 0
rs 9.4285
cc 2
eloc 4
nc 2
nop 2
crap 6
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