|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Lib\Access; |
|
4
|
|
|
|
|
5
|
|
|
class Accessor |
|
6
|
|
|
{ |
|
7
|
|
|
const MODE_READ = 0; |
|
8
|
|
|
const MODE_WRITE = 1; |
|
9
|
|
|
|
|
10
|
|
|
const PREF_GET = "get"; |
|
11
|
|
|
const PREF_HAS = "has"; |
|
12
|
|
|
const PREF_IS = "is"; |
|
13
|
|
|
const PREF_SET = "set"; |
|
14
|
|
|
|
|
15
|
2 |
|
public function readValue($arrayOrObject, $property) |
|
16
|
|
|
{ |
|
17
|
2 |
|
if (\is_array($arrayOrObject)) { |
|
18
|
|
|
return $arrayOrObject[$property]; |
|
19
|
2 |
|
} elseif (\is_object($arrayOrObject)) { |
|
20
|
2 |
|
$method = $this->getMethod($arrayOrObject, $property); |
|
21
|
2 |
|
return $method ? $arrayOrObject->$method() : false; |
|
22
|
|
|
} else { |
|
23
|
|
|
return false; |
|
24
|
|
|
} |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
2 |
|
public function writeValue(&$arrayOrObject, $property, $value) |
|
28
|
|
|
{ |
|
29
|
2 |
|
if (\is_array($arrayOrObject)) { |
|
30
|
|
|
$arrayOrObject[$property] = $value; |
|
31
|
2 |
|
} elseif (\is_object($arrayOrObject)) { |
|
32
|
2 |
|
$method = $this->getMethod($arrayOrObject, $property, self::MODE_WRITE); |
|
33
|
2 |
|
false === $method ?: $arrayOrObject->$method($value); |
|
34
|
|
|
} |
|
35
|
2 |
|
} |
|
36
|
|
|
|
|
37
|
4 |
|
private function getMethod($target, $property, $mode = self::MODE_READ) |
|
38
|
|
|
{ |
|
39
|
4 |
|
$refObject = new \ReflectionClass(get_class($target)); |
|
40
|
4 |
|
$camelized = $this->camelize($property); |
|
41
|
|
|
|
|
42
|
4 |
|
$getter = self::PREF_GET.$camelized; |
|
43
|
4 |
|
$setter = self::PREF_SET.$camelized; |
|
44
|
4 |
|
$hasser = self::PREF_HAS.$camelized; |
|
45
|
4 |
|
$isser = self::PREF_IS.$camelized; |
|
46
|
4 |
|
$getsetter = lcfirst($camelized); |
|
47
|
4 |
|
$magicGet = '__'.self::PREF_GET; |
|
48
|
4 |
|
$magicSet = '__'.self::PREF_SET; |
|
49
|
4 |
|
$magicCall = '__call'; |
|
50
|
|
|
|
|
51
|
|
|
$methods = [ |
|
52
|
4 |
|
self::MODE_READ => [ |
|
53
|
4 |
|
$getter => $getter, |
|
54
|
4 |
|
$hasser => $hasser, |
|
55
|
4 |
|
$isser => $isser, |
|
56
|
4 |
|
$getsetter => $getsetter, |
|
57
|
4 |
|
$magicGet => $getter, |
|
58
|
4 |
|
$magicCall => $getter |
|
59
|
|
|
], |
|
60
|
4 |
|
self::MODE_WRITE => [ |
|
61
|
4 |
|
$setter => $setter, |
|
62
|
4 |
|
$magicSet => $setter, |
|
63
|
4 |
|
$magicCall => $setter |
|
64
|
|
|
] |
|
65
|
|
|
]; |
|
66
|
|
|
|
|
67
|
4 |
|
foreach ($methods[$mode] as $name => $method) { |
|
68
|
4 |
|
if ($refObject->hasMethod($name)) { |
|
69
|
4 |
|
return $method; |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
2 |
|
return false; |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
4 |
|
public function camelize($string) |
|
76
|
|
|
{ |
|
77
|
4 |
|
return str_replace('_', '', ucwords($string, '_')); |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|