diff --git a/EventSubscriber/ContentViewSerializationSubscriber.php b/EventSubscriber/ContentViewSerializationSubscriber.php index 377739c7..1bb255b3 100644 --- a/EventSubscriber/ContentViewSerializationSubscriber.php +++ b/EventSubscriber/ContentViewSerializationSubscriber.php @@ -31,13 +31,7 @@ public static function getSubscribedEvents() return [ [ 'event' => Events::POST_SERIALIZE, - 'format' => 'json', - 'method' => 'onPostSerializeJson', - ], - [ - 'event' => Events::POST_SERIALIZE, - 'format' => 'array', - 'method' => 'onPostSerializeArray', + 'method' => 'onPostSerialize', ], ]; } @@ -67,6 +61,15 @@ public function __construct( $this->contentTypeManager = $contentTypeManager; } + public function onPostSerialize(ObjectEvent $event): void + { + if ($event->getContext()->hasAttribute('array_serializer')) { + $this->onPostSerializeArray($event); + } else { + $this->onPostSerializeJson($event); + } + } + public function onPostSerializeJson(ObjectEvent $event): void { $object = $event->getObject(); diff --git a/Tests/Functional/EventSubscriber/ContentViewSerializationSubscriberTest.php b/Tests/Functional/EventSubscriber/ContentViewSerializationSubscriberTest.php index 0ca07910..b47e97aa 100644 --- a/Tests/Functional/EventSubscriber/ContentViewSerializationSubscriberTest.php +++ b/Tests/Functional/EventSubscriber/ContentViewSerializationSubscriberTest.php @@ -74,4 +74,68 @@ public function testSerializeToJsonMissingField(): void json_decode($result, true) ); } + + public function testSerializeToArray(): void + { + $contentView = new ContentView( + self::RESOURCE_KEY, + '123-123-123', + 'de', + 'default', + ['title' => 'Sulu', 'article' => '

Sulu is awesome

'] + ); + + $result = $this->getContainer()->get('sulu_core.array_serializer')->serialize( + $contentView, + SerializationContext::create()->setSerializeNull(true) + ); + + $this->assertSame( + [ + 'id' => '123-123-123', + 'template' => 'default', + 'content' => [ + 'title' => 'Sulu', + 'article' => '

Sulu is awesome

', + ], + 'view' => [ + 'title' => [], + 'article' => [], + ], + ], + $result + ); + } + + public function testSerializeToArrayMissingField(): void + { + $contentView = new ContentView( + self::RESOURCE_KEY, + '123-123-123', + 'de', + 'default', + ['title' => 'Sulu'] + ); + + $result = $this->getContainer()->get('sulu_core.array_serializer')->serialize( + $contentView, + SerializationContext::create()->setSerializeNull(true) + ); + + $this->assertSame( + [ + 'id' => '123-123-123', + 'template' => 'default', + 'content' => [ + 'title' => 'Sulu', + 'article' => null, + ], + 'view' => [ + 'title' => [], + 'article' => [], + ], + ], + $result + ); + } }