From 5b41d4762869b7dc3dc3008311483a2a7d663ea0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lu=C3=ADs=20Cobucci?= Date: Tue, 27 Mar 2018 00:55:11 +0200 Subject: [PATCH] Add JMS Serializer formatter To server as example of more flexible formatting. --- composer.json | 2 + src/Formatter/JmsSerializer.php | 45 ++++++++++++++++++ tests/Formatter/JmsSerializerTest.php | 67 +++++++++++++++++++++++++++ 3 files changed, 114 insertions(+) create mode 100644 src/Formatter/JmsSerializer.php create mode 100644 tests/Formatter/JmsSerializerTest.php diff --git a/composer.json b/composer.json index fe4c9edd..0ecff003 100644 --- a/composer.json +++ b/composer.json @@ -26,6 +26,7 @@ "require-dev": { "doctrine/coding-standard": "^4.0", "infection/infection": "^0.8", + "jms/serializer": "^1.11", "middlewares/negotiation": "^1.0", "phpstan/phpstan": "^0.10@dev", "phpstan/phpstan-phpunit": "^0.10@dev", @@ -35,6 +36,7 @@ "zendframework/zend-diactoros": "^1.7" }, "suggest": { + "jms/serializer": "For content formatting using a more flexible serializer", "middlewares/negotiation": "For acceptable format identification", "zendframework/zend-diactoros": "For concrete implementation of PSR-7" }, diff --git a/src/Formatter/JmsSerializer.php b/src/Formatter/JmsSerializer.php new file mode 100644 index 00000000..d1abbac9 --- /dev/null +++ b/src/Formatter/JmsSerializer.php @@ -0,0 +1,45 @@ +serializer = $serializer; + $this->format = $format; + } + + /** + * {@inheritdoc} + */ + public function format($content): string + { + try { + return $this->serializer->serialize($content, $this->format); + } catch (Throwable $exception) { + throw new ContentCouldNotBeFormatted( + sprintf('Given content could not be formatted in %s using JMS Serializer', $this->format), + $exception->getCode(), + $exception + ); + } + } +} diff --git a/tests/Formatter/JmsSerializerTest.php b/tests/Formatter/JmsSerializerTest.php new file mode 100644 index 00000000..6f0779e4 --- /dev/null +++ b/tests/Formatter/JmsSerializerTest.php @@ -0,0 +1,67 @@ +serializer = $this->createMock(SerializerInterface::class); + } + + /** + * @test + * + * @covers ::__construct() + * @covers ::format() + */ + public function formatShouldSimplyForwardCallToSerializer(): void + { + $content = ['a' => 'test']; + + $this->serializer->expects(self::once()) + ->method('serialize') + ->with($content, 'json') + ->willReturn('{"a":"test"}'); + + $formatter = new JmsSerializer($this->serializer, 'json'); + + self::assertSame('{"a":"test"}', $formatter->format($content)); + } + + /** + * @test + * + * @covers ::__construct() + * @covers ::format() + */ + public function formatShouldConvertAnyRaisedException(): void + { + $this->expectException(ContentCouldNotBeFormatted::class); + + $this->serializer->method('serialize') + ->willThrowException(new RuntimeException()); + + $formatter = new JmsSerializer($this->serializer, 'json'); + $formatter->format(['a' => 'test']); + } +}