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
|
|
|
|