Chris@0
|
1 <?php
|
Chris@0
|
2
|
Chris@0
|
3 /*
|
Chris@0
|
4 * This file is part of the Symfony package.
|
Chris@0
|
5 *
|
Chris@0
|
6 * (c) Fabien Potencier <fabien@symfony.com>
|
Chris@0
|
7 *
|
Chris@0
|
8 * For the full copyright and license information, please view the LICENSE
|
Chris@0
|
9 * file that was distributed with this source code.
|
Chris@0
|
10 */
|
Chris@0
|
11
|
Chris@0
|
12 namespace Symfony\Component\Serializer\NameConverter;
|
Chris@0
|
13
|
Chris@0
|
14 /**
|
Chris@0
|
15 * CamelCase to Underscore name converter.
|
Chris@0
|
16 *
|
Chris@0
|
17 * @author Kévin Dunglas <dunglas@gmail.com>
|
Chris@0
|
18 */
|
Chris@0
|
19 class CamelCaseToSnakeCaseNameConverter implements NameConverterInterface
|
Chris@0
|
20 {
|
Chris@0
|
21 private $attributes;
|
Chris@0
|
22 private $lowerCamelCase;
|
Chris@0
|
23
|
Chris@0
|
24 /**
|
Chris@17
|
25 * @param array|null $attributes The list of attributes to rename or null for all attributes
|
Chris@0
|
26 * @param bool $lowerCamelCase Use lowerCamelCase style
|
Chris@0
|
27 */
|
Chris@0
|
28 public function __construct(array $attributes = null, $lowerCamelCase = true)
|
Chris@0
|
29 {
|
Chris@0
|
30 $this->attributes = $attributes;
|
Chris@0
|
31 $this->lowerCamelCase = $lowerCamelCase;
|
Chris@0
|
32 }
|
Chris@0
|
33
|
Chris@0
|
34 /**
|
Chris@0
|
35 * {@inheritdoc}
|
Chris@0
|
36 */
|
Chris@0
|
37 public function normalize($propertyName)
|
Chris@0
|
38 {
|
Chris@14
|
39 if (null === $this->attributes || \in_array($propertyName, $this->attributes)) {
|
Chris@14
|
40 return strtolower(preg_replace('/[A-Z]/', '_\\0', lcfirst($propertyName)));
|
Chris@0
|
41 }
|
Chris@0
|
42
|
Chris@0
|
43 return $propertyName;
|
Chris@0
|
44 }
|
Chris@0
|
45
|
Chris@0
|
46 /**
|
Chris@0
|
47 * {@inheritdoc}
|
Chris@0
|
48 */
|
Chris@0
|
49 public function denormalize($propertyName)
|
Chris@0
|
50 {
|
Chris@0
|
51 $camelCasedName = preg_replace_callback('/(^|_|\.)+(.)/', function ($match) {
|
Chris@0
|
52 return ('.' === $match[1] ? '_' : '').strtoupper($match[2]);
|
Chris@0
|
53 }, $propertyName);
|
Chris@0
|
54
|
Chris@0
|
55 if ($this->lowerCamelCase) {
|
Chris@0
|
56 $camelCasedName = lcfirst($camelCasedName);
|
Chris@0
|
57 }
|
Chris@0
|
58
|
Chris@14
|
59 if (null === $this->attributes || \in_array($camelCasedName, $this->attributes)) {
|
Chris@0
|
60 return $camelCasedName;
|
Chris@0
|
61 }
|
Chris@0
|
62
|
Chris@0
|
63 return $propertyName;
|
Chris@0
|
64 }
|
Chris@0
|
65 }
|