| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
namespace Symfony\Component\Serializer\NameConverter; |
| 13 |
|
| 14 |
use Symfony\Component\Serializer\Exception\UnexpectedPropertyException; |
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
> |
| 20 |
|
| 21 |
final class SnakeCaseToCamelCaseNameConverter implements NameConverterInterface |
| 22 |
{ |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
public const REQUIRE_CAMEL_CASE_PROPERTIES = 'require_camel_case_properties'; |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
public function __construct( |
| 33 |
private readonly ?array $attributes = null, |
| 34 |
private readonly bool $lowerCamelCase = true, |
| 35 |
) { |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 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 |
static 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 |
|
| 63 |
|
| 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 |
} |