Skip to content

Commit 82ac336

Browse files
Merge pull request #11 from 21TORR/stdclass
Allow normalizing empty stdClass
2 parents e388018 + 473ce0e commit 82ac336

4 files changed

Lines changed: 44 additions & 3 deletions

File tree

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
1.3.2
2+
=====
3+
4+
* (improvement) Allow normalizing empty `stdClass`.
5+
6+
17
1.3.1
28
=====
39

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
"symfony/http-kernel": "^6.4 || ^7.0"
1818
},
1919
"require-dev": {
20-
"21torr/janus": "^1.3",
20+
"21torr/janus": "^1.4",
2121
"bamarni/composer-bin-plugin": "^1.8",
2222
"doctrine/common": "^3.4",
2323
"roave/security-advisories": "dev-latest",

src/Normalizer/SimpleNormalizer.php

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,13 @@ public function normalize (mixed $value, array $context = []) : mixed
4040

4141
if (\is_object($value))
4242
{
43+
// Allow empty stdClass as a way to force a JSON {} instead of an
44+
// array which would encode to []
45+
if ($value instanceof \stdClass && [] === get_object_vars($value))
46+
{
47+
return $value;
48+
}
49+
4350
try
4451
{
4552
$className = $value::class;
@@ -56,14 +63,14 @@ public function normalize (mixed $value, array $context = []) : mixed
5663
}
5764
catch (ServiceNotFoundException $exception)
5865
{
59-
throw new ObjectTypeNotSupportedException(sprintf(
66+
throw new ObjectTypeNotSupportedException(\sprintf(
6067
"Can't normalize type %s",
6168
get_debug_type($value),
6269
), 0, $exception);
6370
}
6471
}
6572

66-
throw new UnsupportedTypeException(sprintf(
73+
throw new UnsupportedTypeException(\sprintf(
6774
"Can't normalize type %s",
6875
get_debug_type($value),
6976
));

tests/Normalizer/ObjectNormalizationTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,34 @@ public static function getNormalizedType () : string
4343
self::assertSame(["id" => 42], $normalizer->normalize($value));
4444
}
4545

46+
/**
47+
*
48+
*/
49+
public function testEmptyStdClass () : void
50+
{
51+
$normalizer = $this->createNormalizer();
52+
$object = new \stdClass();
53+
54+
self::assertSame(
55+
$object,
56+
$normalizer->normalize($object),
57+
);
58+
}
59+
60+
/**
61+
*
62+
*/
63+
public function testNonEmptyStdClassIsInvalid () : void
64+
{
65+
$normalizer = $this->createNormalizer();
66+
$object = new \stdClass();
67+
$object->prop = 5;
68+
69+
$this->expectException(ObjectTypeNotSupportedException::class);
70+
$this->expectExceptionMessage("Can't normalize type stdClass");
71+
$normalizer->normalize($object);
72+
}
73+
4674
/**
4775
*
4876
*/

0 commit comments

Comments
 (0)