4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Serializer\NameConverter;
15 * CamelCase to Underscore name converter.
17 * @author Kévin Dunglas <dunglas@gmail.com>
19 class CamelCaseToSnakeCaseNameConverter implements NameConverterInterface
29 private $lowerCamelCase;
32 * @param null|array $attributes The list of attributes to rename or null for all attributes
33 * @param bool $lowerCamelCase Use lowerCamelCase style
35 public function __construct(array $attributes = null, $lowerCamelCase = true)
37 $this->attributes = $attributes;
38 $this->lowerCamelCase = $lowerCamelCase;
44 public function normalize($propertyName)
46 if (null === $this->attributes || in_array($propertyName, $this->attributes)) {
47 $lcPropertyName = lcfirst($propertyName);
50 $len = strlen($lcPropertyName);
51 for ($i = 0; $i < $len; ++$i) {
52 if (ctype_upper($lcPropertyName[$i])) {
53 $snakeCasedName .= '_'.strtolower($lcPropertyName[$i]);
55 $snakeCasedName .= strtolower($lcPropertyName[$i]);
59 return $snakeCasedName;
68 public function denormalize($propertyName)
70 $camelCasedName = preg_replace_callback('/(^|_|\.)+(.)/', function ($match) {
71 return ('.' === $match[1] ? '_' : '').strtoupper($match[2]);
74 if ($this->lowerCamelCase) {
75 $camelCasedName = lcfirst($camelCasedName);
78 if (null === $this->attributes || in_array($camelCasedName, $this->attributes)) {
79 return $camelCasedName;