vendor/symfony/serializer/NameConverter/CamelCaseToSnakeCaseNameConverter.php line 28

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