annotate 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
rev   line source
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 /**
Chris@0 22 * @var array|null
Chris@0 23 */
Chris@0 24 private $attributes;
Chris@0 25
Chris@0 26 /**
Chris@0 27 * @var bool
Chris@0 28 */
Chris@0 29 private $lowerCamelCase;
Chris@0 30
Chris@0 31 /**
Chris@0 32 * @param null|array $attributes The list of attributes to rename or null for all attributes
Chris@0 33 * @param bool $lowerCamelCase Use lowerCamelCase style
Chris@0 34 */
Chris@0 35 public function __construct(array $attributes = null, $lowerCamelCase = true)
Chris@0 36 {
Chris@0 37 $this->attributes = $attributes;
Chris@0 38 $this->lowerCamelCase = $lowerCamelCase;
Chris@0 39 }
Chris@0 40
Chris@0 41 /**
Chris@0 42 * {@inheritdoc}
Chris@0 43 */
Chris@0 44 public function normalize($propertyName)
Chris@0 45 {
Chris@0 46 if (null === $this->attributes || in_array($propertyName, $this->attributes)) {
Chris@0 47 $lcPropertyName = lcfirst($propertyName);
Chris@0 48 $snakeCasedName = '';
Chris@0 49
Chris@0 50 $len = strlen($lcPropertyName);
Chris@0 51 for ($i = 0; $i < $len; ++$i) {
Chris@0 52 if (ctype_upper($lcPropertyName[$i])) {
Chris@0 53 $snakeCasedName .= '_'.strtolower($lcPropertyName[$i]);
Chris@0 54 } else {
Chris@0 55 $snakeCasedName .= strtolower($lcPropertyName[$i]);
Chris@0 56 }
Chris@0 57 }
Chris@0 58
Chris@0 59 return $snakeCasedName;
Chris@0 60 }
Chris@0 61
Chris@0 62 return $propertyName;
Chris@0 63 }
Chris@0 64
Chris@0 65 /**
Chris@0 66 * {@inheritdoc}
Chris@0 67 */
Chris@0 68 public function denormalize($propertyName)
Chris@0 69 {
Chris@0 70 $camelCasedName = preg_replace_callback('/(^|_|\.)+(.)/', function ($match) {
Chris@0 71 return ('.' === $match[1] ? '_' : '').strtoupper($match[2]);
Chris@0 72 }, $propertyName);
Chris@0 73
Chris@0 74 if ($this->lowerCamelCase) {
Chris@0 75 $camelCasedName = lcfirst($camelCasedName);
Chris@0 76 }
Chris@0 77
Chris@0 78 if (null === $this->attributes || in_array($camelCasedName, $this->attributes)) {
Chris@0 79 return $camelCasedName;
Chris@0 80 }
Chris@0 81
Chris@0 82 return $propertyName;
Chris@0 83 }
Chris@0 84 }