|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <fabien@symfony.com> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Symfony\Component\Serializer\NameConverter; |
| 13 | + |
| 14 | +use Symfony\Component\Serializer\Exception\UnexpectedPropertyException; |
| 15 | + |
| 16 | +/** |
| 17 | + * Underscore to camelCase name converter. |
| 18 | + * |
| 19 | + * @author Kévin Dunglas <kevin@dunglas.dev> |
| 20 | + */ |
| 21 | +final readonly class SnakeCaseToCamelCaseNameConverter implements NameConverterInterface |
| 22 | +{ |
| 23 | + /** |
| 24 | + * Require all properties to be written in camelCase. |
| 25 | + */ |
| 26 | + public const REQUIRE_CAMEL_CASE_PROPERTIES = 'require_camel_case_properties'; |
| 27 | + |
| 28 | + /** |
| 29 | + * @param string[]|null $attributes The list of attributes to rename or null for all attributes |
| 30 | + * @param bool $lowerCamelCase Use lowerCamelCase style |
| 31 | + */ |
| 32 | + public function __construct( |
| 33 | + private ?array $attributes = null, |
| 34 | + private bool $lowerCamelCase = true, |
| 35 | + ) { |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * @param class-string|null $class |
| 40 | + * @param array<string, mixed> $context |
| 41 | + */ |
| 42 | + public function normalize(string $propertyName, ?string $class = null, ?string $format = null, array $context = []): string |
| 43 | + { |
| 44 | + if (null !== $this->attributes && !\in_array($propertyName, $this->attributes, true)) { |
| 45 | + return $propertyName; |
| 46 | + } |
| 47 | + |
| 48 | + $camelCasedName = preg_replace_callback( |
| 49 | + '/(^|_|\.)+(.)/', |
| 50 | + fn ($match) => ('.' === $match[1] ? '_' : '').strtoupper($match[2]), |
| 51 | + $propertyName |
| 52 | + ); |
| 53 | + |
| 54 | + if ($this->lowerCamelCase) { |
| 55 | + $camelCasedName = lcfirst($camelCasedName); |
| 56 | + } |
| 57 | + |
| 58 | + return $camelCasedName; |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * @param class-string|null $class |
| 63 | + * @param array<string, mixed> $context |
| 64 | + */ |
| 65 | + public function denormalize(string $propertyName, ?string $class = null, ?string $format = null, array $context = []): string |
| 66 | + { |
| 67 | + if (($context[self::REQUIRE_CAMEL_CASE_PROPERTIES] ?? false) && $propertyName !== $this->normalize($propertyName, $class, $format, $context)) { |
| 68 | + throw new UnexpectedPropertyException($propertyName); |
| 69 | + } |
| 70 | + |
| 71 | + $snakeCased = strtolower(preg_replace('/[A-Z]/', '_\\0', lcfirst($propertyName))); |
| 72 | + if (null === $this->attributes || \in_array($snakeCased, $this->attributes, true)) { |
| 73 | + return $snakeCased; |
| 74 | + } |
| 75 | + |
| 76 | + return $propertyName; |
| 77 | + } |
| 78 | +} |
0 commit comments