|
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
|
|
|
* @internal |
|
22
|
|
|
*/ |
|
23
|
|
|
class CamelKeysNormalizer implements ArrayNormalizerInterface |
|
24
|
|
|
{ |
|
25
|
|
|
/** |
|
26
|
|
|
* {@inheritdoc} |
|
27
|
|
|
*/ |
|
28
|
7 |
|
public function normalize(array $data) |
|
29
|
|
|
{ |
|
30
|
7 |
|
$this->normalizeArray($data); |
|
31
|
|
|
|
|
32
|
6 |
|
return $data; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
7 |
|
private function normalizeArray(array &$data) |
|
36
|
|
|
{ |
|
37
|
7 |
|
$normalizedData = array(); |
|
38
|
|
|
|
|
39
|
7 |
|
foreach ($data as $key => $val) { |
|
40
|
5 |
|
$normalizedKey = $this->normalizeString($key); |
|
41
|
|
|
|
|
42
|
5 |
|
if ($normalizedKey !== $key) { |
|
43
|
5 |
|
if (array_key_exists($normalizedKey, $normalizedData)) { |
|
44
|
1 |
|
throw new NormalizationException(sprintf('The key "%s" is invalid as it will override the existing key "%s"', $key, $normalizedKey)); |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
5 |
|
$normalizedData[$normalizedKey] = $val; |
|
49
|
5 |
|
$key = $normalizedKey; |
|
50
|
|
|
|
|
51
|
5 |
|
if (is_array($val)) { |
|
52
|
3 |
|
$this->normalizeArray($normalizedData[$key]); |
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
6 |
|
$data = $normalizedData; |
|
57
|
6 |
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* Normalizes a string. |
|
61
|
|
|
* |
|
62
|
|
|
* @return string |
|
63
|
|
|
*/ |
|
64
|
5 |
|
protected function normalizeString(string $string) |
|
65
|
|
|
{ |
|
66
|
5 |
|
if (false === strpos($string, '_')) { |
|
67
|
3 |
|
return $string; |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
return preg_replace_callback('/_([a-zA-Z0-9])/', function ($matches) { |
|
71
|
5 |
|
return strtoupper($matches[1]); |
|
72
|
5 |
|
}, $string); |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|