Skip to content

Commit

Permalink
Allow null to be visited if is a root object
Browse files Browse the repository at this point in the history
  • Loading branch information
goetas committed Sep 12, 2020
1 parent 4fe470c commit 258fa11
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/GraphNavigator/SerializationGraphNavigator.php
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ public function accept($data, ?array $type = null)

switch ($type['name']) {
case 'NULL':
if (!$this->shouldSerializeNull) {
if (!$this->shouldSerializeNull && !$this->isRootNullAllowed()) {
throw new NotAcceptableException();
}
return $this->visitor->visitNull($data, $type);
Expand Down Expand Up @@ -259,6 +259,11 @@ public function accept($data, ?array $type = null)
}
}

private function isRootNullAllowed(): bool
{
return $this->context->hasAttribute('allows_root_null') && $this->context->getAttribute('allows_root_null') && 0 === $this->context->getVisitingSet()->count();
}

private function afterVisitingObject(ClassMetadata $metadata, object $object, array $type): void
{
$this->context->stopVisiting($object);
Expand Down
11 changes: 11 additions & 0 deletions tests/Serializer/BaseSerializationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,17 @@ public function testSerializeNullArray()
);
}

public function testSerializeNullRoot()
{
$context = SerializationContext::create()
->setAttribute('allows_root_null', true);

self::assertEquals(
$this->getContent('nullable_root'),
$this->serializer->serialize(null, $this->getFormat(), $context)
);
}

public function testNoMetadataNeededWhenDeSerializingNotUsedProperty()
{
/** @var ParentNoMetadataChildObject $dObj */
Expand Down
1 change: 1 addition & 0 deletions tests/Serializer/JsonSerializationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ protected function getContent($key)
static $outputs = [];

if (!$outputs) {
$outputs['nullable_root'] = 'null';
$outputs['readonly'] = '{"id":123,"full_name":"Ruud Kamphuis"}';
$outputs['string'] = '"foo"';
$outputs['boolean_true'] = 'true';
Expand Down
2 changes: 2 additions & 0 deletions tests/Serializer/xml/nullable_root.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<result xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>

0 comments on commit 258fa11

Please sign in to comment.