11
11
12
12
namespace Symfony \Component \Serializer \NameConverter ;
13
13
14
+ use Symfony \Component \Serializer \Exception \NotNormalizableValueException ;
15
+
14
16
/**
15
17
* CamelCase to Underscore name converter.
16
18
*
17
19
* @author Kévin Dunglas <dunglas@gmail.com>
20
+ * @author Aurélien Pillevesse <aurelienpillevesse@hotmail.fr>
18
21
*/
19
- class CamelCaseToSnakeCaseNameConverter implements NameConverterInterface
22
+ class CamelCaseToSnakeCaseNameConverter implements AdvancedNameConverterInterface
20
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
+
21
29
/**
22
30
* @param array|null $attributes The list of attributes to rename or null for all attributes
23
31
* @param bool $lowerCamelCase Use lowerCamelCase style
@@ -28,7 +36,7 @@ public function __construct(
28
36
) {
29
37
}
30
38
31
- public function normalize (string $ propertyName ): string
39
+ public function normalize (string $ propertyName, ? string $ class = null , ? string $ format = null , array $ context = [] ): string
32
40
{
33
41
if (null === $ this ->attributes || \in_array ($ propertyName , $ this ->attributes , true )) {
34
42
return strtolower (preg_replace ('/[A-Z]/ ' , '_ \\0 ' , lcfirst ($ propertyName )));
@@ -37,8 +45,12 @@ public function normalize(string $propertyName): string
37
45
return $ propertyName ;
38
46
}
39
47
40
- public function denormalize (string $ propertyName ): string
48
+ public function denormalize (string $ propertyName, ? string $ class = null , ? string $ format = null , array $ context = [] ): string
41
49
{
50
+ if (($ context [self ::REQUIRE_SNAKE_CASE_PROPERTIES ] ?? false ) && $ propertyName !== $ this ->normalize ($ propertyName , $ class , $ format , $ context )) {
51
+ throw new NotNormalizableValueException ('Could not denormalize property, snake case format accepted only. ' );
52
+ }
53
+
42
54
$ camelCasedName = preg_replace_callback ('/(^|_|\.)+(.)/ ' , fn ($ match ) => ('. ' === $ match [1 ] ? '_ ' : '' ).strtoupper ($ match [2 ]), $ propertyName );
43
55
44
56
if ($ this ->lowerCamelCase ) {
0 commit comments