Completed
Push — master ( 665986...1514e7 )
by Guilh
08:09 queued 05:04
created

CamelKeysNormalizer::normalizeArray()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 27
ccs 19
cts 19
cp 1
rs 8.439
cc 5
eloc 15
nc 6
nop 1
crap 5
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 7
    public function normalize(array $data)
27
    {
28 7
        $this->normalizeArray($data);
29
30 6
        return $data;
31
    }
32
33
    /**
34
     * Normalizes an array.
35
     *
36
     * @param array &$data
37
     *
38
     * @throws Exception\NormalizationException
39
     */
40 7
    private function normalizeArray(array &$data)
41
    {
42 7
        $normalizedData = array();
43
44 7
        foreach ($data as $key => $val) {
45 5
            $normalizedKey = $this->normalizeString($key);
46
47 5
            if ($normalizedKey !== $key) {
48 5
                if (array_key_exists($normalizedKey, $normalizedData)) {
49 1
                    throw new NormalizationException(sprintf(
50 1
                        'The key "%s" is invalid as it will override the existing key "%s"',
51 1
                        $key,
52
                        $normalizedKey
53 1
                    ));
54
                }
55 5
            }
56
57 5
            $normalizedData[$normalizedKey] = $val;
58 5
            $key = $normalizedKey;
59
60 5
            if (is_array($val)) {
61 3
                $this->normalizeArray($normalizedData[$key]);
62 2
            }
63 7
        }
64
65 6
        $data = $normalizedData;
66 6
    }
67
68
    /**
69
     * Normalizes a string.
70
     *
71
     * @param string $string
72
     *
73
     * @return string
74
     */
75 5
    protected function normalizeString($string)
76
    {
77 5
        if (false === strpos($string, '_')) {
78 3
            return $string;
79
        }
80
81 5
        return preg_replace_callback('/_([a-zA-Z0-9])/', function ($matches) {
82 5
            return strtoupper($matches[1]);
83 5
        }, $string);
84
    }
85
}
86