comparison vendor/symfony/serializer/NameConverter/CamelCaseToSnakeCaseNameConverter.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children 1fec387a4317
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.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 Symfony\Component\Serializer\NameConverter;
13
14 /**
15 * CamelCase to Underscore name converter.
16 *
17 * @author Kévin Dunglas <dunglas@gmail.com>
18 */
19 class CamelCaseToSnakeCaseNameConverter implements NameConverterInterface
20 {
21 /**
22 * @var array|null
23 */
24 private $attributes;
25
26 /**
27 * @var bool
28 */
29 private $lowerCamelCase;
30
31 /**
32 * @param null|array $attributes The list of attributes to rename or null for all attributes
33 * @param bool $lowerCamelCase Use lowerCamelCase style
34 */
35 public function __construct(array $attributes = null, $lowerCamelCase = true)
36 {
37 $this->attributes = $attributes;
38 $this->lowerCamelCase = $lowerCamelCase;
39 }
40
41 /**
42 * {@inheritdoc}
43 */
44 public function normalize($propertyName)
45 {
46 if (null === $this->attributes || in_array($propertyName, $this->attributes)) {
47 $lcPropertyName = lcfirst($propertyName);
48 $snakeCasedName = '';
49
50 $len = strlen($lcPropertyName);
51 for ($i = 0; $i < $len; ++$i) {
52 if (ctype_upper($lcPropertyName[$i])) {
53 $snakeCasedName .= '_'.strtolower($lcPropertyName[$i]);
54 } else {
55 $snakeCasedName .= strtolower($lcPropertyName[$i]);
56 }
57 }
58
59 return $snakeCasedName;
60 }
61
62 return $propertyName;
63 }
64
65 /**
66 * {@inheritdoc}
67 */
68 public function denormalize($propertyName)
69 {
70 $camelCasedName = preg_replace_callback('/(^|_|\.)+(.)/', function ($match) {
71 return ('.' === $match[1] ? '_' : '').strtoupper($match[2]);
72 }, $propertyName);
73
74 if ($this->lowerCamelCase) {
75 $camelCasedName = lcfirst($camelCasedName);
76 }
77
78 if (null === $this->attributes || in_array($camelCasedName, $this->attributes)) {
79 return $camelCasedName;
80 }
81
82 return $propertyName;
83 }
84 }