forked from yiisoft/yii-cycle
/
BaseConfig.php
78 lines (69 loc) · 2.29 KB
/
BaseConfig.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
namespace Yiisoft\Yii\Cycle\Config;
use Yiisoft\Yii\Cycle\Config\Exception\PropertyNotFoundException;
class BaseConfig
{
public function __get($name)
{
$getter = 'get' . ucfirst($name);
if (method_exists($this, $getter)) {
return $this->$getter();
}
if (property_exists($this, $name)) {
return $this->$name;
}
throw new PropertyNotFoundException("The `$name` property not found in a " . static::class . " object");
}
public function __call($name, $arguments)
{
$prefix = substr($name, 0, 3);
if ($prefix === 'get') {
$prop = lcfirst(substr($name, 3));
if (!property_exists($this, $prop)) {
throw new PropertyNotFoundException("The `$name` property was not found when the `$name` method was called");
}
return $this->$prop;
}
throw new \BadMethodCallException();
}
public function configure(array $params): void
{
foreach ($params as $name => $value) {
$setter = 'set' . ucfirst($name);
if (method_exists($this, $setter)) {
$this->$setter($value);
} elseif (property_exists($this, $name)) {
$this->$name = $value;
} else {
throw new PropertyNotFoundException("The `$name` property not found when configure " . static::class . " object");
}
}
}
/**
* Return all public and protected properties as array.
* Property values will be obtained using getter methods.
* Note: all private properties will be ignored!
* @return array
* @throws PropertyNotFoundException
*/
public function toArray(): array
{
$result = [];
$arrayed = (array)$this;
$keys = array_keys($arrayed);
foreach ($keys as $key) {
if ($key[0] !== chr(0)) {
// public property
$result[$key] = $this->__get($key);
} elseif ($key[1] === '*') {
// protected property
$key = substr($key, 3);
$result[$key] = $this->__get($key);
} else {
// private property
// ignore
}
}
return $result;
}
}