CamelCaseToSnakeCaseNameConverter.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 = null, bool $lowerCamelCase = true)
  25. {
  26. $this->attributes = $attributes;
  27. $this->lowerCamelCase = $lowerCamelCase;
  28. }
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function normalize(string $propertyName)
  33. {
  34. if (null === $this->attributes || \in_array($propertyName, $this->attributes)) {
  35. return strtolower(preg_replace('/[A-Z]/', '_\\0', lcfirst($propertyName)));
  36. }
  37. return $propertyName;
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function denormalize(string $propertyName)
  43. {
  44. $camelCasedName = preg_replace_callback('/(^|_|\.)+(.)/', function ($match) {
  45. return ('.' === $match[1] ? '_' : '').strtoupper($match[2]);
  46. }, $propertyName);
  47. if ($this->lowerCamelCase) {
  48. $camelCasedName = lcfirst($camelCasedName);
  49. }
  50. if (null === $this->attributes || \in_array($camelCasedName, $this->attributes)) {
  51. return $camelCasedName;
  52. }
  53. return $propertyName;
  54. }
  55. }