1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Dwo\SimpleAccessor; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Class SimpleAccessor |
7
|
|
|
* |
8
|
|
|
* @author Dave Www <[email protected]> |
9
|
|
|
*/ |
10
|
|
|
class SimpleAccessor |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @param mixed $objectOrArray |
14
|
|
|
* @param string $propertyPath |
15
|
|
|
* @param bool $throwIfNotFound |
16
|
|
|
* |
17
|
|
|
* @return mixed |
18
|
|
|
*/ |
19
|
|
|
public static function getValueFromPath($objectOrArray, $propertyPath, $throwIfNotFound = false) |
20
|
|
|
{ |
21
|
|
|
if(null !== $value = self::getValue($objectOrArray, $propertyPath)) { |
22
|
|
|
return $value; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
$paths = explode('.', $propertyPath); |
26
|
|
|
$lastPath = array_pop($paths); |
27
|
|
|
|
28
|
|
|
$pathReady = []; |
29
|
|
|
foreach ($paths as $path) { |
30
|
|
|
$pathReady[] = $path; |
31
|
|
|
|
32
|
|
|
$objectOrArray = self::getValue($objectOrArray, $path); |
33
|
|
|
|
34
|
|
|
if (null === $objectOrArray || is_scalar($objectOrArray)) { |
35
|
|
|
if ($throwIfNotFound) { |
36
|
|
|
throw new \Exception(sprintf('path not found: %s', implode('.', $pathReady))); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
return null; |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
return self::getValue($objectOrArray, $lastPath); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @param mixed $objectOrArray |
48
|
|
|
* @param string $property |
49
|
|
|
* |
50
|
|
|
* @return mixed |
51
|
|
|
*/ |
52
|
|
|
public static function getValue($objectOrArray, $property) |
53
|
|
|
{ |
54
|
|
|
$propertyValue = null; |
55
|
|
|
|
56
|
|
|
if (is_object($objectOrArray)) { |
57
|
|
|
|
58
|
|
|
$camelProp = str_replace(' ', '', ucwords(str_replace('_', ' ', $property))); |
59
|
|
|
$methods = array('get'.$camelProp, lcfirst($camelProp), 'is'.$camelProp, 'has'.$camelProp); |
60
|
|
|
|
61
|
|
|
foreach ($methods as $method) { |
62
|
|
|
if (method_exists($objectOrArray, $method)) { |
63
|
|
|
$propertyValue = $objectOrArray->$method(); |
64
|
|
|
break; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
if (null === $propertyValue && property_exists($objectOrArray, $property)) { |
69
|
|
|
$propertyValue = $objectOrArray->$property; |
70
|
|
|
} |
71
|
|
|
} elseif (is_array($objectOrArray)) { |
72
|
|
|
if (isset($objectOrArray[$property])) { |
73
|
|
|
$propertyValue = $objectOrArray[$property]; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
return $propertyValue; |
78
|
|
|
} |
79
|
|
|
} |