1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Ivory Google Map package. |
5
|
|
|
* |
6
|
|
|
* (c) Eric GELOEN <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please read the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Ivory\GoogleMap\Service\Utility; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @author GeLo <[email protected]> |
16
|
|
|
*/ |
17
|
|
|
class XmlParser |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @param string $xml |
21
|
|
|
* @param string[] $rules |
22
|
|
|
* @param bool $snakeToCamelCase |
23
|
|
|
* |
24
|
|
|
* @return mixed[] |
25
|
|
|
*/ |
26
|
|
|
public function parse($xml, array $rules = [], $snakeToCamelCase = false) |
27
|
|
|
{ |
28
|
|
|
return $this->pluralize( |
29
|
|
|
json_decode(json_encode(new \SimpleXMLElement($xml)), true), |
30
|
|
|
$rules, |
31
|
|
|
$snakeToCamelCase |
32
|
|
|
); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @param mixed[] $xml |
37
|
|
|
* @param string[] $rules |
38
|
|
|
* @param bool $snakeToCamelCase |
39
|
|
|
* |
40
|
|
|
* @return mixed[] |
41
|
|
|
*/ |
42
|
|
|
private function pluralize(array $xml, array $rules, $snakeToCamelCase) |
43
|
|
|
{ |
44
|
|
|
foreach ($xml as $attribute => $value) { |
45
|
|
|
if (isset($rules[$attribute])) { |
46
|
|
|
$xml[$rules[$attribute]] = $value; |
47
|
|
|
unset($xml[$attribute]); |
48
|
|
|
|
49
|
|
|
$attribute = $rules[$attribute]; |
50
|
|
|
|
51
|
|
|
if (!is_array($value) || is_string(key($value))) { |
52
|
|
|
$xml[$attribute] = [$value]; |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
if (is_array($xml[$attribute])) { |
57
|
|
|
$xml[$attribute] = $this->pluralize($xml[$attribute], $rules, $snakeToCamelCase); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
if ($snakeToCamelCase |
61
|
|
|
&& is_string($attribute) |
62
|
|
|
&& ($newAttribute = $this->convertSnakeToCamelCase($attribute)) !== $attribute |
63
|
|
|
) { |
64
|
|
|
$xml[$newAttribute] = $xml[$attribute]; |
65
|
|
|
unset($xml[$attribute]); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return $xml; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @param string $value |
74
|
|
|
* |
75
|
|
|
* @return string |
76
|
|
|
*/ |
77
|
|
|
private function convertSnakeToCamelCase($value) |
78
|
|
|
{ |
79
|
|
|
return lcfirst(implode('', array_map(function ($word) { |
80
|
|
|
return ucfirst($word); |
81
|
|
|
}, explode('_', $value)))); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|