1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the FOSRestBundle package. |
5
|
|
|
* |
6
|
|
|
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace FOS\RestBundle\Normalizer; |
13
|
|
|
|
14
|
|
|
use FOS\RestBundle\Normalizer\Exception\NormalizationException; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Normalizes the array by changing its keys from underscore to camel case. |
18
|
|
|
* |
19
|
|
|
* @author Florian Voutzinos <[email protected]> |
20
|
|
|
*/ |
21
|
|
|
class CamelKeysNormalizer implements ArrayNormalizerInterface |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* {@inheritdoc} |
25
|
|
|
*/ |
26
|
5 |
|
public function normalize(array $data) |
27
|
|
|
{ |
28
|
5 |
|
$this->normalizeArray($data); |
29
|
|
|
|
30
|
4 |
|
return $data; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Normalizes an array. |
35
|
|
|
* |
36
|
|
|
* @param array &$data |
37
|
|
|
* |
38
|
|
|
* @throws Exception\NormalizationException |
39
|
|
|
*/ |
40
|
5 |
|
private function normalizeArray(array &$data) |
41
|
|
|
{ |
42
|
5 |
|
foreach ($data as $key => $val) { |
43
|
3 |
|
$normalizedKey = $this->normalizeString($key); |
44
|
|
|
|
45
|
3 |
|
if ($normalizedKey !== $key) { |
46
|
3 |
|
if (array_key_exists($normalizedKey, $data)) { |
47
|
1 |
|
throw new NormalizationException(sprintf( |
48
|
1 |
|
'The key "%s" is invalid as it will override the existing key "%s"', |
49
|
1 |
|
$key, |
50
|
|
|
$normalizedKey |
51
|
1 |
|
)); |
52
|
|
|
} |
53
|
|
|
|
54
|
3 |
|
unset($data[$key]); |
55
|
3 |
|
$data[$normalizedKey] = $val; |
56
|
3 |
|
$key = $normalizedKey; |
57
|
3 |
|
} |
58
|
|
|
|
59
|
3 |
|
if (is_array($val)) { |
60
|
3 |
|
$this->normalizeArray($data[$key]); |
61
|
2 |
|
} |
62
|
5 |
|
} |
63
|
4 |
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* Normalizes a string. |
67
|
|
|
* |
68
|
|
|
* @param string $string |
69
|
|
|
* |
70
|
|
|
* @return string |
71
|
|
|
*/ |
72
|
3 |
|
protected function normalizeString($string) |
73
|
|
|
{ |
74
|
3 |
|
if (false === strpos($string, '_')) { |
75
|
2 |
|
return $string; |
76
|
|
|
} |
77
|
|
|
|
78
|
3 |
|
if (preg_match('/^(_+)(.*)/', $string, $matches)) { |
79
|
|
|
$underscorePrefix = $matches[1]; |
80
|
|
|
$string = $matches[2]; |
81
|
|
|
} else { |
82
|
3 |
|
$underscorePrefix = ''; |
83
|
|
|
} |
84
|
|
|
|
85
|
3 |
|
$string = preg_replace_callback('/_([a-zA-Z0-9])/', function ($matches) { |
86
|
3 |
|
return strtoupper($matches[1]); |
87
|
3 |
|
}, $string); |
88
|
|
|
|
89
|
3 |
|
return $underscorePrefix.$string; |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|