diff --git a/CHANGELOG.md b/CHANGELOG.md index c2bbd8d..4409a40 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +1.3.2 +===== + +* (improvement) Allow normalizing empty `stdClass`. + + 1.3.1 ===== diff --git a/composer.json b/composer.json index 6c9c11e..db9537f 100644 --- a/composer.json +++ b/composer.json @@ -17,7 +17,7 @@ "symfony/http-kernel": "^6.4 || ^7.0" }, "require-dev": { - "21torr/janus": "^1.3", + "21torr/janus": "^1.4", "bamarni/composer-bin-plugin": "^1.8", "doctrine/common": "^3.4", "roave/security-advisories": "dev-latest", diff --git a/src/Normalizer/SimpleNormalizer.php b/src/Normalizer/SimpleNormalizer.php index e62c3ba..72dde2d 100644 --- a/src/Normalizer/SimpleNormalizer.php +++ b/src/Normalizer/SimpleNormalizer.php @@ -40,6 +40,13 @@ public function normalize (mixed $value, array $context = []) : mixed if (\is_object($value)) { + // Allow empty stdClass as a way to force a JSON {} instead of an + // array which would encode to [] + if ($value instanceof \stdClass && [] === get_object_vars($value)) + { + return $value; + } + try { $className = $value::class; @@ -56,14 +63,14 @@ public function normalize (mixed $value, array $context = []) : mixed } catch (ServiceNotFoundException $exception) { - throw new ObjectTypeNotSupportedException(sprintf( + throw new ObjectTypeNotSupportedException(\sprintf( "Can't normalize type %s", get_debug_type($value), ), 0, $exception); } } - throw new UnsupportedTypeException(sprintf( + throw new UnsupportedTypeException(\sprintf( "Can't normalize type %s", get_debug_type($value), )); diff --git a/tests/Normalizer/ObjectNormalizationTest.php b/tests/Normalizer/ObjectNormalizationTest.php index f15f87c..c15e848 100644 --- a/tests/Normalizer/ObjectNormalizationTest.php +++ b/tests/Normalizer/ObjectNormalizationTest.php @@ -43,6 +43,34 @@ public static function getNormalizedType () : string self::assertSame(["id" => 42], $normalizer->normalize($value)); } + /** + * + */ + public function testEmptyStdClass () : void + { + $normalizer = $this->createNormalizer(); + $object = new \stdClass(); + + self::assertSame( + $object, + $normalizer->normalize($object), + ); + } + + /** + * + */ + public function testNonEmptyStdClassIsInvalid () : void + { + $normalizer = $this->createNormalizer(); + $object = new \stdClass(); + $object->prop = 5; + + $this->expectException(ObjectTypeNotSupportedException::class); + $this->expectExceptionMessage("Can't normalize type stdClass"); + $normalizer->normalize($object); + } + /** * */