From f0a867b20f0547586a290ab9cb23646afdf69e28 Mon Sep 17 00:00:00 2001 From: Sami Mazouz Date: Sun, 6 Nov 2022 19:56:07 +0100 Subject: [PATCH] chore: throw an exception when no serializer is provided to the controller (#3614) * chore: throw an exception when no serializer is provided to the controller Signed-off-by: Sami Mazouz * test: no serializer set throws exception Signed-off-by: Sami Mazouz Signed-off-by: Sami Mazouz Signed-off-by: Sami Mazouz --- .../AbstractSerializeController.php | 5 ++ .../api/AbstractSerializeControllerTest.php | 52 +++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 framework/core/tests/integration/api/AbstractSerializeControllerTest.php diff --git a/framework/core/src/Api/Controller/AbstractSerializeController.php b/framework/core/src/Api/Controller/AbstractSerializeController.php index 0c813eabf..cd13ff5c2 100644 --- a/framework/core/src/Api/Controller/AbstractSerializeController.php +++ b/framework/core/src/Api/Controller/AbstractSerializeController.php @@ -14,6 +14,7 @@ use Illuminate\Contracts\Container\Container; use Illuminate\Database\Eloquent\Collection; use Illuminate\Support\Arr; use Illuminate\Support\Str; +use InvalidArgumentException; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; @@ -122,6 +123,10 @@ abstract class AbstractSerializeController implements RequestHandlerInterface } } + if (empty($this->serializer)) { + throw new InvalidArgumentException('Serializer required for controller: '.static::class); + } + $serializer = static::$container->make($this->serializer); $serializer->setRequest($request); diff --git a/framework/core/tests/integration/api/AbstractSerializeControllerTest.php b/framework/core/tests/integration/api/AbstractSerializeControllerTest.php new file mode 100644 index 000000000..af009f134 --- /dev/null +++ b/framework/core/tests/integration/api/AbstractSerializeControllerTest.php @@ -0,0 +1,52 @@ +extend( + (new Extend\Routes('api')) + ->get('/dummy-serialize', 'dummy-serialize', DummySerializeController::class) + ); + + $response = $this->send( + $this->request('GET', '/api/dummy-serialize') + ); + + $json = json_decode((string) $response->getBody(), true); + + $this->assertEquals(500, $response->getStatusCode()); + $this->assertStringStartsWith('InvalidArgumentException: Serializer required for controller: '.DummySerializeController::class, $json['errors'][0]['detail']); + } +} + +class DummySerializeController extends AbstractSerializeController +{ + public $serializer = null; + + protected function data(ServerRequestInterface $request, Document $document) + { + return []; + } + + protected function createElement($data, SerializerInterface $serializer) + { + return $data; + } +}