| 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 |
|
| 22 |
class CamelCaseToSnakeCaseNameConverter implements NameConverterInterface |
| 23 |
{ |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
public const REQUIRE_SNAKE_CASE_PROPERTIES = 'require_snake_case_properties'; |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
public function __construct( |
| 34 |
private ?array $attributes = null, |
| 35 |
private bool $lowerCamelCase = true, |
| 36 |
) { |
| 37 |
} |
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
public function normalize(string $propertyName): string |
| 45 |
{ |
| 46 |
if (null === $this->attributes || \in_array($propertyName, $this->attributes, true)) { |
| 47 |
return strtolower(preg_replace('/[A-Z]/', '_\\0', lcfirst($propertyName))); |
| 48 |
} |
| 49 |
|
| 50 |
return $propertyName; |
| 51 |
} |
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
public function denormalize(string $propertyName): string |
| 59 |
{ |
| 60 |
$class = 1 < \func_num_args() ? func_get_arg(1) : null; |
| 61 |
$format = 2 < \func_num_args() ? func_get_arg(2) : null; |
| 62 |
$context = 3 < \func_num_args() ? func_get_arg(3) : []; |
| 63 |
|
| 64 |
if (($context[self::REQUIRE_SNAKE_CASE_PROPERTIES] ?? false) && $propertyName !== $this->normalize($propertyName, $class, $format, $context)) { |
| 65 |
throw new UnexpectedPropertyException($propertyName); |
| 66 |
} |
| 67 |
|
| 68 |
$camelCasedName = preg_replace_callback('/(^|_|\.)+(.)/', static fn ($match) => ('.' === $match[1] ? '_' : '').strtoupper($match[2]), $propertyName); |
| 69 |
|
| 70 |
if ($this->lowerCamelCase) { |
| 71 |
$camelCasedName = lcfirst($camelCasedName); |
| 72 |
} |
| 73 |
|
| 74 |
if (null === $this->attributes || \in_array($camelCasedName, $this->attributes, true)) { |
| 75 |
return $camelCasedName; |
| 76 |
} |
| 77 |
|
| 78 |
return $propertyName; |
| 79 |
} |
| 80 |
} |