From 587c69e2b25a5f21d5ff65ed17637fdef68038c2 Mon Sep 17 00:00:00 2001 From: Connor Bell Date: Thu, 5 May 2022 00:02:27 +0100 Subject: [PATCH] [Fix] Override default Laravel method to check the type is an exact match, otherwise return 406. Addresses #184 --- src/Http/Requests/ResourceQuery.php | 12 ++++++++++ tests/lib/Acceptance/ResponseTest.php | 32 +++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/src/Http/Requests/ResourceQuery.php b/src/Http/Requests/ResourceQuery.php index dfd5074..3ebcb99 100644 --- a/src/Http/Requests/ResourceQuery.php +++ b/src/Http/Requests/ResourceQuery.php @@ -315,6 +315,18 @@ protected function mediaTypes(): array return $this->mediaTypes; } + /** + * Determine if the given content types match. + * + * @param string $actual + * @param string $type + * @return bool + */ + public static function matchesType($actual, $type) + { + return $actual === $type; + } + /** * Get an exception if the media type is not acceptable. * diff --git a/tests/lib/Acceptance/ResponseTest.php b/tests/lib/Acceptance/ResponseTest.php index 99d60bb..f751268 100644 --- a/tests/lib/Acceptance/ResponseTest.php +++ b/tests/lib/Acceptance/ResponseTest.php @@ -20,6 +20,7 @@ namespace LaravelJsonApi\Laravel\Tests\Acceptance; use App\Models\Post; +use Illuminate\Http\Response; use Illuminate\Support\Facades\Route; use LaravelJsonApi\Core\Responses\DataResponse; use LaravelJsonApi\Core\Responses\ErrorResponse; @@ -95,4 +96,35 @@ public function testErrors(): void $response->assertExactErrorStatus($error); } + + public function testValidHeader(): void + { + Route::get('/test', fn() => []); + + $response = $this + ->withoutExceptionHandling() + ->jsonApi() + ->get('/test'); + + $response->assertStatusCode(Response::HTTP_OK); + } + + public function testInvalidHeader(): void + { + $error = [ + 'status' => '406', + 'title' => 'The requested resource is capable of generating only content not acceptable according to the Accept headers sent in the request.' + ]; + + Route::get('/test', fn() => ErrorResponse::error($error)); + + $response = $this + ->withoutExceptionHandling() + ->jsonApi() + ->withHeader('Accepts', 'application/json') + ->get('/test'); + + $response->assertExactErrorStatus($error); + $response->assertStatusCode(Response::HTTP_NOT_ACCEPTABLE); + } }