Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
1.3.2
=====

* (improvement) Allow normalizing empty `stdClass`.


1.3.1
=====

Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
11 changes: 9 additions & 2 deletions src/Normalizer/SimpleNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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),
));
Expand Down
28 changes: 28 additions & 0 deletions tests/Normalizer/ObjectNormalizationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

/**
*
*/
Expand Down