-
Notifications
You must be signed in to change notification settings - Fork 0
/
Getter.php
61 lines (53 loc) · 1.42 KB
/
Getter.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
<?php
namespace b2r\Component\SimpleAccessor;
use b2r\Component\Exception\InvalidPropertyException;
/**
* Simple property getter trait
*/
trait Getter
{
public function __get($name)
{
return $this->getPropertyValue($name);
}
/**
* Get property value
*
* #### $options defaults
* ```php
* $options = [
* 'default' => null, # Undefined property default value
* 'prefixes' => ['get'], # Getter method prefixes
* 'read' => true, # Read private/protected property?
* 'strict' => true, # Thorw exception?
* ]
* ```
* @param string $name
* @param array|null $options
*/
protected function getPropertyValue($name, array $options = null)
{
$o = [
'default' => null,
'prefixes' => ['get'],
'read' => true,
'strict' => true,
];
if ($options) {
$o = array_merge($o, $options);
}
foreach ($o['prefixes'] as $prefix) {
$method = $prefix . $name;
if (method_exists($this, $method)) {
return $this->$method();
}
}
if ($o['read'] && property_exists($this, $name)) {
return $this->$name;
}
if ($o['strict']) {
throw new InvalidPropertyException($this, $name);
}
return $o['default'];
}
}