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