1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace WebservicesNl\Utils; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Class EntityUtils. |
7
|
|
|
*/ |
8
|
|
|
class EntityUtils |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* Extract the value of a property from an entity. |
12
|
|
|
* |
13
|
|
|
* @param mixed $entity |
14
|
|
|
* @param string $property |
15
|
|
|
* |
16
|
|
|
* @throws \InvalidArgumentException |
17
|
|
|
* |
18
|
|
|
* @return mixed |
19
|
|
|
*/ |
20
|
4 |
|
public static function extractValueFromEntity($entity, $property) |
21
|
|
|
{ |
22
|
4 |
|
$getter = self::createGetter($entity, $property); |
23
|
|
|
|
24
|
4 |
|
return $entity->$getter(); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @param mixed $entity |
29
|
|
|
* @param string $property |
30
|
|
|
* |
31
|
|
|
* @throws \InvalidArgumentException |
32
|
|
|
* |
33
|
|
|
* @return string |
34
|
|
|
*/ |
35
|
4 |
|
public static function createGetter($entity, $property) |
36
|
|
|
{ |
37
|
4 |
|
$prefixes = ['get', 'is', 'has']; |
38
|
4 |
|
foreach ($prefixes as $prefix) { |
39
|
4 |
|
$getter = $prefix . ucfirst($property); |
40
|
4 |
|
if (is_callable([$entity, $getter])) { |
41
|
3 |
|
return $getter; |
42
|
|
|
} |
43
|
2 |
|
} |
44
|
|
|
|
45
|
1 |
|
if (is_callable([$entity, $property])) { |
46
|
1 |
|
return $property; |
47
|
|
|
} |
48
|
|
|
|
49
|
1 |
|
throw new \InvalidArgumentException( |
50
|
1 |
|
sprintf('No getter found for property %s in class %s', $property, get_class($entity)) |
51
|
1 |
|
); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @param mixed $entity |
56
|
|
|
* @param string $property |
57
|
|
|
* @param mixed $value |
58
|
|
|
* |
59
|
|
|
* @throws \InvalidArgumentException |
60
|
|
|
*/ |
61
|
1 |
|
public static function setValueInEntity($entity, $property, $value) |
62
|
|
|
{ |
63
|
1 |
|
$setter = self::createSetter($entity, $property); |
64
|
1 |
|
$entity->$setter($value); |
65
|
1 |
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @param mixed $entity |
69
|
|
|
* @param string $property |
70
|
|
|
* |
71
|
|
|
* @throws \InvalidArgumentException |
72
|
|
|
* |
73
|
|
|
* @return string |
74
|
|
|
*/ |
75
|
1 |
|
public static function createSetter($entity, $property) |
76
|
|
|
{ |
77
|
1 |
|
$setter = 'set' . ucfirst($property); |
78
|
1 |
|
if (false === is_callable([$entity, $setter])) { |
79
|
1 |
|
throw new \InvalidArgumentException( |
80
|
1 |
|
sprintf('No setter found for property %s in class %s', $property, get_class($entity)) |
81
|
1 |
|
); |
82
|
|
|
} |
83
|
|
|
|
84
|
1 |
|
return $setter; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|