CamelCaseToSnakeCaseNameConverter.php 2.2 KB

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