From 62f7bb48072177cc81f95338138378b9ce8b42b9 Mon Sep 17 00:00:00 2001 From: Greg Tyler Date: Mon, 11 Nov 2024 15:27:31 +0000 Subject: [PATCH] Support value types in serialization Allows serialization of value types (i.e. `true` and `false`, as opposed to `bool`), including in union types (e.g. `string|false`). Otherwise, tries to create class with FQCN "true" and, for union types, filters out value types as non-primitive. Fixes #1568 --- .../SerializationGraphNavigator.php | 2 ++ src/Metadata/Driver/TypedPropertiesDriver.php | 2 ++ .../TypedProperties/UnionTypedProperties.php | 2 ++ .../Driver/UnionTypedPropertiesDriverTest.php | 25 +++++++++++++++++++ 4 files changed, 31 insertions(+) diff --git a/src/GraphNavigator/SerializationGraphNavigator.php b/src/GraphNavigator/SerializationGraphNavigator.php index 52d1543da..431eba7d0 100644 --- a/src/GraphNavigator/SerializationGraphNavigator.php +++ b/src/GraphNavigator/SerializationGraphNavigator.php @@ -156,6 +156,8 @@ public function accept($data, ?array $type = null) case 'bool': case 'boolean': + case 'true': + case 'false': return $this->visitor->visitBoolean((bool) $data, $type); case 'double': diff --git a/src/Metadata/Driver/TypedPropertiesDriver.php b/src/Metadata/Driver/TypedPropertiesDriver.php index 15c4f9d67..2e7af8a66 100644 --- a/src/Metadata/Driver/TypedPropertiesDriver.php +++ b/src/Metadata/Driver/TypedPropertiesDriver.php @@ -75,6 +75,8 @@ private function getDefaultWhiteList(): array 'float', 'bool', 'boolean', + 'true', + 'false', 'string', 'double', 'iterable', diff --git a/tests/Fixtures/TypedProperties/UnionTypedProperties.php b/tests/Fixtures/TypedProperties/UnionTypedProperties.php index d7f40dde2..f88de896b 100644 --- a/tests/Fixtures/TypedProperties/UnionTypedProperties.php +++ b/tests/Fixtures/TypedProperties/UnionTypedProperties.php @@ -10,6 +10,8 @@ class UnionTypedProperties private int|bool|float|string|null $nullableData; + private string|false $valueTypedUnion; + public function __construct($data) { $this->data = $data; diff --git a/tests/Metadata/Driver/UnionTypedPropertiesDriverTest.php b/tests/Metadata/Driver/UnionTypedPropertiesDriverTest.php index 5fbfd0935..1da90bfd4 100644 --- a/tests/Metadata/Driver/UnionTypedPropertiesDriverTest.php +++ b/tests/Metadata/Driver/UnionTypedPropertiesDriverTest.php @@ -57,6 +57,31 @@ public function testInferUnionTypesShouldResultInManyTypes() ); } + public function testInferUnionTypesShouldIncludeValueTypes() + { + $m = $this->resolve(UnionTypedProperties::class); + + self::assertEquals( + [ + 'name' => 'union', + 'params' => + [ + [ + [ + 'name' => 'string', + 'params' => [], + ], + [ + 'name' => 'false', + 'params' => [], + ], + ], + ], + ], + $m->propertyMetadata['valueTypedUnion']->type, + ); + } + private function resolve(string $classToResolve): ClassMetadata { $namingStrategy = new IdenticalPropertyNamingStrategy();