Passed
Pull Request — master (#5)
by
unknown
01:34
created

BaseConfig::__call()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 7
c 0
b 0
f 0
nc 3
nop 2
dl 0
loc 11
ccs 0
cts 11
cp 0
crap 12
rs 10
1
<?php
2
3
namespace Yiisoft\Yii\Cycle\Config;
4
5
use Yiisoft\Yii\Cycle\Config\Exception\PropertyNotFoundException;
6
7
class BaseConfig
8
{
9
    public function __construct(Params $params)
10
    {
11
        $this->configure($params->get(static::class, []));
12
    }
13
14
    public function __get($name)
15
    {
16
        $getter = 'get' . ucfirst($name);
17
        if (method_exists($this, $getter)) {
18
            return $this->$getter();
19
        }
20
        if (property_exists($this, $name)) {
21
            return $this->$name;
22
        }
23
        throw new PropertyNotFoundException("Not found the property `$name` in a " . static::class . " object");
24
    }
25
26
    public function __call($name, $arguments)
27
    {
28
        $prefix = substr($name, 0, 3);
29
        if ($prefix === 'get') {
30
            $prop = lcfirst(substr($name, 3));
31
            if (!property_exists($this, $prop)) {
32
                throw new PropertyNotFoundException("The property `$prop` was not found when the `$name` method was called");
33
            }
34
            return $this->$prop;
35
        }
36
        throw new \BadMethodCallException();
37
    }
38
39
    public function configure(array $params): void
40
    {
41
        foreach ($params as $name => $value) {
42
            $setter = 'set' . ucfirst($name);
43
            if (method_exists($this, $setter)) {
44
                $this->$setter($value);
45
            } elseif (property_exists($this, $name)) {
46
                $this->$name = $value;
47
            } else {
48
                throw new PropertyNotFoundException("Not found the property `$name` when configure " . static::class . " object");
49
            }
50
        }
51
    }
52
53
    public function toArray(): array
54
    {
55
        $result = [];
56
        $arrayed = (array)$this;
57
        $keys = array_keys($arrayed);
58
        foreach ($keys as $key) {
59
            if ($key[0] !== chr(0)) {
60
                // public property
61
62
                $result[$key] = $this->__get($key);
63
            } elseif ($key[1] === '*') {
64
                // protected property
65
66
                $key = substr($key, 3);
67
                $result[$key] = $this->__get($key);
68
            } else {
69
                // private property
70
71
                // ignore
72
            }
73
        }
74
        return $result;
75
    }
76
}
77