Skip to content

Commit

Permalink
do not hide Exceptions from custom handlers but correctly handle null
Browse files Browse the repository at this point in the history
  • Loading branch information
Hikariii committed Mar 11, 2020
1 parent 0e28668 commit 693717f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/GraphNavigator/SerializationGraphNavigator.php
Original file line number Diff line number Diff line change
Expand Up @@ -195,9 +195,11 @@ public function accept($data, ?array $type = null)
if (null !== $handler = $this->handlerRegistry->getHandler(GraphNavigatorInterface::DIRECTION_SERIALIZATION, $type['name'], $this->format)) {
try {
$rs = \call_user_func($handler, $this->visitor, $data, $type, $this->context);
} finally {
} catch (NotAcceptableException $e) {
$this->context->stopVisiting($data);
throw $e;
}
$this->context->stopVisiting($data);

return $rs;
}
Expand Down
32 changes: 32 additions & 0 deletions tests/Serializer/GraphNavigatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use JMS\Serializer\SerializationContext;
use JMS\Serializer\Visitor\DeserializationVisitorInterface;
use JMS\Serializer\Visitor\SerializationVisitorInterface;
use JMS\Serializer\VisitorInterface;
use Metadata\MetadataFactory;
use PHPUnit\Framework\TestCase;

Expand Down Expand Up @@ -131,6 +132,37 @@ public function testNavigatorChangeTypeOnSerialization()
$navigator->accept($object, null);
}

public function testExposeAcceptHandlerExceptionOnSerialization()
{
$object = new SerializableClass();
$typeName = 'JsonSerializable';
$format = 'foo';
$msg = 'Useful serialization error with relevant context information';

$handler = static function ($visitor, $data, array $type, SerializationContext $context) use ($msg) {
$context->startVisiting(new \stdClass());
throw new \RuntimeException($msg);
};
$this->handlerRegistry->registerHandler(GraphNavigatorInterface::DIRECTION_SERIALIZATION, $typeName, $format, $handler);

$visitor = $this->createMock(VisitorInterface::class);
$context = $this->getMockBuilder(SerializationContext::class)
->enableOriginalConstructor()
->setMethodsExcept(['initialize', 'startVisiting', 'stopVisiting'])
->getMock();
$context->method('getFormat')->willReturn($format);

$navigator = new SerializationGraphNavigator($this->metadataFactory, $this->handlerRegistry, $this->accessor, $this->dispatcher);
$navigator->initialize($this->serializationVisitor, $context);
$context->initialize($format, $visitor, $navigator, $this->metadataFactory);

try {
$navigator->accept($object, ['name' => $typeName, 'params' => []]);
} catch (\RuntimeException $exception) {
$this->assertEquals($msg, $exception->getMessage());
}
}

protected function setUp(): void
{
$this->deserializationVisitor = $this->getMockBuilder(DeserializationVisitorInterface::class)->getMock();
Expand Down

0 comments on commit 693717f

Please sign in to comment.