1
|
|
|
<?php |
2
|
|
|
namespace Fathomminds\Rest\Helpers; |
3
|
|
|
|
4
|
|
|
use Fathomminds\Rest\Exceptions\RestException; |
5
|
|
|
|
6
|
|
|
abstract class ObjectMapper |
7
|
|
|
{ |
8
|
3 |
|
public static function map($object, $map) |
9
|
|
|
{ |
10
|
3 |
|
if (gettype($object) !== 'object') { |
11
|
1 |
|
throw new RestException('ObjectMapper map method expects object as first parameter', [ |
12
|
1 |
|
'parameter' => $object, |
13
|
|
|
]); |
14
|
|
|
} |
15
|
2 |
|
if (!is_array($map)) { |
16
|
1 |
|
throw new RestException('ObjectMapper map method expects array as second parameter', [ |
17
|
1 |
|
'parameter' => $map, |
18
|
|
|
]); |
19
|
|
|
} |
20
|
1 |
|
$mappedObject = new \StdClass(); |
21
|
1 |
|
foreach ($map as $targetFieldName => $sourceFieldName) { |
22
|
1 |
|
list($propertyExists, $propertyValue) = static::getPropertyValue($object, $sourceFieldName); |
|
|
|
|
23
|
1 |
|
if ($propertyExists) { |
24
|
1 |
|
$mappedObject = static::setPropertyValue( |
|
|
|
|
25
|
1 |
|
$mappedObject, |
26
|
1 |
|
$targetFieldName, |
27
|
1 |
|
$propertyValue |
28
|
|
|
); |
29
|
|
|
} |
30
|
|
|
} |
31
|
1 |
|
return $mappedObject; |
32
|
|
|
} |
33
|
|
|
|
34
|
1 |
|
private static function setPropertyValue($mappedObject, $targetFieldName, $propertyValue) |
35
|
|
|
{ |
36
|
1 |
|
$fieldNameArr = explode('.', $targetFieldName); |
37
|
1 |
|
$fieldName = array_shift($fieldNameArr); |
38
|
1 |
|
if (count($fieldNameArr) !== 0) { |
39
|
1 |
|
if (!property_exists($mappedObject, $fieldName)) { |
40
|
1 |
|
$mappedObject->{$fieldName} = new \StdClass(); |
41
|
|
|
} |
42
|
1 |
|
$mappedObject->{$fieldName} = static::setPropertyValue( |
|
|
|
|
43
|
1 |
|
$mappedObject->{$fieldName}, |
44
|
1 |
|
implode('.', $fieldNameArr), |
45
|
1 |
|
$propertyValue |
46
|
|
|
); |
47
|
1 |
|
return $mappedObject; |
48
|
|
|
} |
49
|
1 |
|
$mappedObject->{$fieldName} = $propertyValue; |
50
|
1 |
|
return $mappedObject; |
51
|
|
|
} |
52
|
|
|
|
53
|
1 |
|
private static function getPropertyValue($object, $sourceFieldName) |
54
|
|
|
{ |
55
|
1 |
|
$fieldNameArr = explode('.', $sourceFieldName); |
56
|
1 |
|
$fieldName = array_shift($fieldNameArr); |
57
|
1 |
|
if (!property_exists($object, $fieldName)) { |
58
|
|
|
return [ |
59
|
1 |
|
false, |
60
|
|
|
null |
61
|
|
|
]; |
62
|
|
|
} |
63
|
1 |
|
if (count($fieldNameArr) === 0) { |
64
|
|
|
return [ |
65
|
1 |
|
true, |
66
|
1 |
|
json_decode(json_encode($object->{$fieldName})) |
67
|
|
|
]; |
68
|
|
|
} |
69
|
1 |
|
return static::getPropertyValue($object->{$fieldName}, implode('.', $fieldNameArr)); |
|
|
|
|
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
Let’s assume you have a class which uses late-static binding:
}
The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the
getSomeVariable()
on that sub-class, you will receive a runtime error:In the case above, it makes sense to update
SomeClass
to useself
instead: