Drupal investigation

CamelCaseToSnakeCaseNameConverter.php 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. $lcPropertyName = lcfirst($propertyName);
  42. $snakeCasedName = '';
  43. $len = strlen($lcPropertyName);
  44. for ($i = 0; $i < $len; ++$i) {
  45. if (ctype_upper($lcPropertyName[$i])) {
  46. $snakeCasedName .= '_'.strtolower($lcPropertyName[$i]);
  47. } else {
  48. $snakeCasedName .= strtolower($lcPropertyName[$i]);
  49. }
  50. }
  51. return $snakeCasedName;
  52. }
  53. return $propertyName;
  54. }
  55. /**
  56. * {@inheritdoc}
  57. */
  58. public function denormalize($propertyName)
  59. {
  60. $camelCasedName = preg_replace_callback('/(^|_|\.)+(.)/', function ($match) {
  61. return ('.' === $match[1] ? '_' : '').strtoupper($match[2]);
  62. }, $propertyName);
  63. if ($this->lowerCamelCase) {
  64. $camelCasedName = lcfirst($camelCasedName);
  65. }
  66. if (null === $this->attributes || in_array($camelCasedName, $this->attributes)) {
  67. return $camelCasedName;
  68. }
  69. return $propertyName;
  70. }
  71. }