Debian Codegraph @

lib/3rdParty/composer/symfony/serializer/NameConverter/CamelCaseToSnakeCaseNameConverter.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
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 * CamelCase to Underscore name converter.
18 *
19 * @author Kévin Dunglas <[email protected]>
20 * @author Aurélien Pillevesse <[email protected]>
21 */
22 class CamelCaseToSnakeCaseNameConverter implements NameConverterInterface
23 {
24 /**
25 * Require all properties to be written in snake_case.
26 */
27 public const REQUIRE_SNAKE_CASE_PROPERTIES = 'require_snake_case_properties';
28
29 /**
30 * @param string[]|null $attributes The list of attributes to rename or null for all attributes
31 * @param bool $lowerCamelCase Use lowerCamelCase style
32 */
33 public function __construct(
34 private ?array $attributes = null,
35 private bool $lowerCamelCase = true,
36 ) {
37 }
38
39 /**
40 * @param class-string|null $class
41 * @param string|null $format
42 * @param array<string, mixed> $context
43 */
44 public function normalize(string $propertyName/* , ?string $class = null, ?string $format = null, array $context = [] */): 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 * @param class-string|null $class
55 * @param string|null $format
56 * @param array<string, mixed> $context
57 */
58 public function denormalize(string $propertyName/* , ?string $class = null, ?string $format = null, array $context = [] */): 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 }