diff --git a/CHANGELOG.md b/CHANGELOG.md index 7800259..2985fa1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,10 @@ ### Unreleased +* Add ResponseFactory helper class for creating simple response objects. +* Add HealthOKHandler for returning a simple 200 OK response to a GET, and NotFoundHandler to return a plain-text + 404 response. +* Add RequestMethodGuardTrait that handlers can use to ensure that the incoming request is an allowed method, returns 405 if not. * [BREAKING]: Handler factory functions now take HandlerFactoryArgs instead of LoggerInterface, this allows us to also pass the request, to allow for simple routing to different handlers. * [BREAKING]: Added strict types and array shapes throughout. diff --git a/src/Const/RequestMethod.php b/src/Const/RequestMethod.php new file mode 100644 index 0000000..836e51b --- /dev/null +++ b/src/Const/RequestMethod.php @@ -0,0 +1,19 @@ +guardRequestMethod($request, RequestMethod::GET) + ?? ResponseFactory::text('OK', 200); + } +} diff --git a/src/Handler/NotFoundHandler.php b/src/Handler/NotFoundHandler.php new file mode 100644 index 0000000..456593c --- /dev/null +++ b/src/Handler/NotFoundHandler.php @@ -0,0 +1,25 @@ +guardRequestMethod($request, RequestMethod::GET) + * ?? ResponseFactory::text('Great! This is an allowed method!'); + * } + * } + */ +trait RequestMethodGuardTrait +{ + private function guardRequestMethod(ServerRequestInterface $request, RequestMethod $allowedMethod, RequestMethod ...$allowedMethods): ?ResponseInterface + { + array_unshift($allowedMethods, $allowedMethod); + $allowedMethodStrs = array_map(fn (RequestMethod $method) => $method->value, $allowedMethods); + + if (in_array(strtoupper($request->getMethod()), $allowedMethodStrs)) { + return null; + } + + return ResponseFactory::text('Method not allowed', status: 405, headers: ['Allow' => implode(',', $allowedMethodStrs)]); + } +} diff --git a/src/ResponseFactory.php b/src/ResponseFactory.php new file mode 100644 index 0000000..0363882 --- /dev/null +++ b/src/ResponseFactory.php @@ -0,0 +1,45 @@ +|string> $headers + */ + public static function text(string $content, int $status = 200, array $headers = []): Response + { + return new Response( + $status, + ['Content-Type' => 'text/plain', ...$headers], + $content + ); + } + + /** + * Shorthand to create an application/json response. + * + * @param array|string> $headers + * + * @throws JsonException + */ + public static function json(mixed $content, int $status = 200, array $headers = []): Response + { + return new Response( + $status, + ['Content-Type' => 'application/json', ...$headers], + json_encode($content, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES) + ); + } +} diff --git a/test/unit/AssertResponse.php b/test/unit/AssertResponse.php new file mode 100644 index 0000000..9f6b47c --- /dev/null +++ b/test/unit/AssertResponse.php @@ -0,0 +1,38 @@ +> $expectHeaders + */ + public static function isExactly( + int $expectStatus, + string $expectBody, + array $expectHeaders, + ResponseInterface $actual, + ): void { + // Ensure body has not been read elsewhere + $actual->getBody()->rewind(); + Assert::assertSame( + [ + 'status' => $expectStatus, + 'body' => $expectBody, + 'headers' => $expectHeaders, + ], + [ + 'status' => $actual->getStatusCode(), + 'body' => $actual->getBody()->getContents(), + 'headers' => $actual->getHeaders(), + ] + ); + // Rewind for any further reads + $actual->getBody()->rewind(); + } +} diff --git a/test/unit/Handler/HealthOKHandlerTest.php b/test/unit/Handler/HealthOKHandlerTest.php new file mode 100644 index 0000000..97564ea --- /dev/null +++ b/test/unit/Handler/HealthOKHandlerTest.php @@ -0,0 +1,61 @@ +assertInstanceOf(RequestHandler::class, $this->newSubject()); + } + + public function testItReturns200OKForGetRequest(): void + { + $request = new ServerRequest('GET', '/healthz'); + + $response = $this->newSubject()->handle($request); + AssertResponse::isExactly(200, 'OK', ['Content-Type' => ['text/plain']], $response); + } + + /** + * @return Iterator + */ + public static function provider_disallowed_methods(): Iterator + { + // Two is enough to prove the point + yield ['POST']; + yield ['HEAD']; + } + + #[DataProvider('provider_disallowed_methods')] + public function testItReturns405MethodNotAllowedForNonGetRequests(string $method): void + { + $request = new ServerRequest($method, '/healthz'); + $response = $this->newSubject()->handle($request); + + AssertResponse::isExactly( + 405, + 'Method not allowed', + [ + 'Content-Type' => ['text/plain'], + 'Allow' => ['GET'], + ], + $response + ); + } + + private function newSubject(): HealthOKHandler + { + return new HealthOKHandler(); + } +} diff --git a/test/unit/Handler/NotFoundHandlerTest.php b/test/unit/Handler/NotFoundHandlerTest.php new file mode 100644 index 0000000..ceb70c8 --- /dev/null +++ b/test/unit/Handler/NotFoundHandlerTest.php @@ -0,0 +1,37 @@ +assertInstanceOf(RequestHandler::class, $this->newSubject()); + } + + public function testItReturns404NotFoundResponse(): void + { + $request = new ServerRequest('GET', '/any-path'); + $response = $this->newSubject()->handle($request); + + AssertResponse::isExactly( + 404, + 'Not Found', + ['Content-Type' => ['text/plain']], + $response + ); + } + + private function newSubject(): NotFoundHandler + { + return new NotFoundHandler(); + } +} diff --git a/test/unit/Handler/Trait/RequestMethodGuardTraitTest.php b/test/unit/Handler/Trait/RequestMethodGuardTraitTest.php new file mode 100644 index 0000000..5b43311 --- /dev/null +++ b/test/unit/Handler/Trait/RequestMethodGuardTraitTest.php @@ -0,0 +1,98 @@ +}> + */ + public static function provider_matching_methods(): Iterator + { + yield 'matches single method' => ['GET', [RequestMethod::GET]]; + yield 'matches one of a list of methods (first)' => ['GET', [RequestMethod::GET, RequestMethod::POST]]; + yield 'matches one of a list of methods (second)' => ['POST', [RequestMethod::GET, RequestMethod::POST]]; + yield 'lowercase get' => ['get', [RequestMethod::GET]]; + yield 'mixed case post' => ['pOsT', [RequestMethod::POST]]; + yield 'uppercase delete' => ['DELETE', [RequestMethod::DELETE]]; + } + + /** + * @param list $allowedMethods + */ + #[DataProvider('provider_matching_methods')] + public function testItReturnsNullWhenMethodMatchesAllowedMethod(string $requestMethod, array $allowedMethods): void + { + $subject = $this->newSubject(); + $request = $this->newRequest($requestMethod); + + $this->assertNull($subject->guardRequestMethod($request, ...$allowedMethods)); + } + + /** + * @return Iterator, string}> + */ + public static function provider_not_matching(): Iterator + { + yield 'does not match single method' => ['POST', [RequestMethod::GET], 'GET']; + yield 'arbitrary unknown method' => ['JUNK', [RequestMethod::GET], 'GET']; + yield 'not in a list of methods (comma-separated Allow response header)' => [ + 'POST', + [RequestMethod::GET, RequestMethod::DELETE], + 'GET,DELETE', + ]; + } + + /** + * @param list $allowedMethods + */ + #[DataProvider('provider_not_matching')] + public function testItReturns405ResponseWhenRequestMethodNotAllowed( + string $requestMethod, + array $allowedMethods, + string $expectAllowHeader, + ): void { + $request = $this->newRequest($requestMethod); + + $response = $this->newSubject()->guardRequestMethod($request, ...$allowedMethods); + + $this->assertInstanceOf(ResponseInterface::class, $response); + AssertResponse::isExactly( + 405, + 'Method not allowed', + ['Content-Type' => ['text/plain'], 'Allow' => [$expectAllowHeader]], + $response, + ); + } + + private function newRequest(string $method): ServerRequestInterface + { + $request = $this->createMock(ServerRequestInterface::class); + $request->method('getMethod')->willReturn($method); + + return $request; + } + + private function newSubject(): RequestMethodGuardTestSubject + { + return new RequestMethodGuardTestSubject(); + } +} + +final class RequestMethodGuardTestSubject +{ + use RequestMethodGuardTrait { + guardRequestMethod as public; + } +} diff --git a/test/unit/ResponseFactoryTest.php b/test/unit/ResponseFactoryTest.php new file mode 100644 index 0000000..f620971 --- /dev/null +++ b/test/unit/ResponseFactoryTest.php @@ -0,0 +1,117 @@ + ['text/plain']], + $response + ); + } + + public function testItCreatesPlainTextResponseWithCustomStatus(): void + { + $response = ResponseFactory::text('Created successfully', 201); + AssertResponse::isExactly( + 201, + 'Created successfully', + ['Content-Type' => ['text/plain']], + $response + ); + } + + public function testItCreatesPlainTextResponseWithCustomHeaders(): void + { + $response = ResponseFactory::text('OK', 200, ['X-Custom-Header' => 'custom-value']); + AssertResponse::isExactly( + 200, + 'OK', + ['Content-Type' => ['text/plain'], 'X-Custom-Header' => ['custom-value']], + $response + ); + } + + public function testItsTextAllowsOverridingContentTypeHeader(): void + { + $response = ResponseFactory::text('custom', 200, ['Content-Type' => 'text/plain; charset=utf-8']); + AssertResponse::isExactly( + 200, + 'custom', + ['Content-Type' => ['text/plain; charset=utf-8']], + $response + ); + } + + public function testItCreatesJsonResponseWithDefaults(): void + { + $response = ResponseFactory::json(['message' => 'Hello world']); + AssertResponse::isExactly( + 200, + '{"message":"Hello world"}', + ['Content-Type' => ['application/json']], + $response + ); + } + + public function testItCreatesJsonResponseWithCustomStatus(): void + { + $response = ResponseFactory::json(['id' => 123], 201); + AssertResponse::isExactly( + 201, + '{"id":123}', + ['Content-Type' => ['application/json']], + $response + ); + } + + public function testItCreatesJsonResponseWithCustomHeaders(): void + { + $response = ResponseFactory::json(['ok' => true], 200, ['X-Custom-Header' => 'custom-value']); + AssertResponse::isExactly( + 200, + '{"ok":true}', + ['Content-Type' => ['application/json'], 'X-Custom-Header' => ['custom-value']], + $response + ); + } + + public function testItsJsonAllowsOverridingContentTypeHeader(): void + { + $response = ResponseFactory::json(['error' => 'Not Found'], 404, ['Content-Type' => 'application/problem+json']); + AssertResponse::isExactly( + 404, + '{"error":"Not Found"}', + ['Content-Type' => ['application/problem+json']], + $response + ); + } + + public function testItDoesNotEscapeSlashesInJsonResponse(): void + { + $response = ResponseFactory::json(['url' => 'https://example.com/api/v1/resource']); + AssertResponse::isExactly( + 200, + '{"url":"https://example.com/api/v1/resource"}', + ['Content-Type' => ['application/json']], + $response + ); + } + + public function testItThrowsJsonExceptionOnJsonError(): void + { + $this->expectException(JsonException::class); + ResponseFactory::json(NAN); + } +}