PropertyTrait::__set()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 0
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
crap 2
1
<?php declare(strict_types=1);
2
3
namespace Benrowe\Properties;
4
5
/**
6
 * Property Trait
7
 * A convenience trait to bolt-in the property manager into an existing class
8
 *
9
 * @package Benrowe\Properties
10
 * @method Property addProperty(string $name, string|null|\Closure $type = null, mixed $default = null)
11 3
 * @method Property getProperty(string $name)
12
 * @method bool hasProperty(string $name)
13 3
 * @method Property[] allProperties()
14 3
 * @method bool removeProperty(string $name)
15
 * @method mixed getValue(string $name)
16
 * @method void setValue(string $name, $value)
17 3
 * @method array allValues()
18
 */
19
trait PropertyTrait
20 6
{
21
    private $propertyManager;
22 6
23
    /**
24
     * Conveniently delegate any method calls to the property manager if they
25 3
     * don't exist in the parent class
26
     */
27 3
    public function __call($methodName, $params)
28
    {
29
        $pm = $this->getPropertyManager();
30 6
        if (!method_exists($pm, $methodName)) {
31
            throw new \Exception('Unknown method '.$methodName);
32 6
        }
33 6
        return call_user_func_array([$pm, $methodName], $params);
34
    }
35 6
36
    /**
37
     *
38
     */
39
    public function __get($key)
40
    {
41
        return $this->getPropertyManager()->getValue($key);
42
    }
43
44
    public function __set($key, $value)
45
    {
46
        return $this->getPropertyManager()->setValue($key, $value);
47
    }
48
49
    /**
50
     * Get an instance of the property manager
51
     *
52
     * @return Manager
53
     */
54
    private function getPropertyManager(): Manager
55
    {
56
        if (!$this->propertyManager) {
57
            $this->propertyManager = new Manager;
58
        }
59
        return $this->propertyManager;
60
    }
61
}
62