From 577f8cb6ec4a9cf69fd5e42de2e90ba00b8ca1e1 Mon Sep 17 00:00:00 2001 From: acoulton Date: Thu, 5 Nov 2026 18:19:33 +0000 Subject: [PATCH 1/3] feat: Add simple helpers for healthcheck, "Not Found" and text responses Simple request handlers that can be used by projects that don't require anything more complex, and a factory function to provide a shorthand for making a text response. --- CHANGELOG.md | 4 + src/Const/RequestMethod.php | 19 ++++ src/Handler/HealthOKHandler.php | 29 ++++++ src/Handler/NotFoundHandler.php | 25 ++++++ src/Handler/Trait/RequestMethodGuardTrait.php | 39 ++++++++ src/ResponseFactory.php | 28 ++++++ test/unit/AssertResponse.php | 38 ++++++++ test/unit/Handler/HealthOKHandlerTest.php | 61 +++++++++++++ test/unit/Handler/NotFoundHandlerTest.php | 37 ++++++++ .../Trait/RequestMethodGuardTraitTest.php | 90 +++++++++++++++++++ test/unit/ResponseFactoryTest.php | 55 ++++++++++++ 11 files changed, 425 insertions(+) create mode 100644 src/Const/RequestMethod.php create mode 100644 src/Handler/HealthOKHandler.php create mode 100644 src/Handler/NotFoundHandler.php create mode 100644 src/Handler/Trait/RequestMethodGuardTrait.php create mode 100644 src/ResponseFactory.php create mode 100644 test/unit/AssertResponse.php create mode 100644 test/unit/Handler/HealthOKHandlerTest.php create mode 100644 test/unit/Handler/NotFoundHandlerTest.php create mode 100644 test/unit/Handler/Trait/RequestMethodGuardTraitTest.php create mode 100644 test/unit/ResponseFactoryTest.php 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..40f3c97 --- /dev/null +++ b/src/ResponseFactory.php @@ -0,0 +1,28 @@ +|string> $headers + */ + public static function text(string $content, int $status = 200, array $headers = []): Response + { + return new Response( + $status, + ['Content-Type' => 'text/plain', ...$headers], + $content + ); + } +} 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..296e30d --- /dev/null +++ b/test/unit/Handler/Trait/RequestMethodGuardTraitTest.php @@ -0,0 +1,90 @@ +}> + */ + 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 = new ServerRequest($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 = new ServerRequest($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 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..db2fa6d --- /dev/null +++ b/test/unit/ResponseFactoryTest.php @@ -0,0 +1,55 @@ + ['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 + ); + } +} From 244e32578895f452fd0c1dd8dbf0308b528c0765 Mon Sep 17 00:00:00 2001 From: acoulton Date: Thu, 5 Nov 2026 18:22:00 +0000 Subject: [PATCH 2/3] feat: Add helper for making JSON responses Which is the other common response type that we need. --- src/ResponseFactory.php | 17 +++++++++ test/unit/ResponseFactoryTest.php | 62 +++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) diff --git a/src/ResponseFactory.php b/src/ResponseFactory.php index 40f3c97..0363882 100644 --- a/src/ResponseFactory.php +++ b/src/ResponseFactory.php @@ -5,6 +5,7 @@ namespace Ingenerator\MicroFramework; use GuzzleHttp\Psr7\Response; +use JsonException; final class ResponseFactory { @@ -25,4 +26,20 @@ public static function text(string $content, int $status = 200, array $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/ResponseFactoryTest.php b/test/unit/ResponseFactoryTest.php index db2fa6d..f620971 100644 --- a/test/unit/ResponseFactoryTest.php +++ b/test/unit/ResponseFactoryTest.php @@ -5,6 +5,7 @@ namespace test\unit; use Ingenerator\MicroFramework\ResponseFactory; +use JsonException; use PHPUnit\Framework\TestCase; final class ResponseFactoryTest extends TestCase @@ -52,4 +53,65 @@ public function testItsTextAllowsOverridingContentTypeHeader(): void $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); + } } From 6a948e10382cf2ba2f9341efac9684f5f95cb16b Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 6 Nov 2026 09:15:56 +0000 Subject: [PATCH 3/3] Avoid deprecated PSR-7 method construction in tests Co-authored-by: acoulton <416566+acoulton@users.noreply.github.com> --- .../Handler/Trait/RequestMethodGuardTraitTest.php | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/test/unit/Handler/Trait/RequestMethodGuardTraitTest.php b/test/unit/Handler/Trait/RequestMethodGuardTraitTest.php index 296e30d..5b43311 100644 --- a/test/unit/Handler/Trait/RequestMethodGuardTraitTest.php +++ b/test/unit/Handler/Trait/RequestMethodGuardTraitTest.php @@ -4,13 +4,13 @@ namespace test\unit\Handler\Trait; -use GuzzleHttp\Psr7\ServerRequest; use Ingenerator\MicroFramework\Const\RequestMethod; use Ingenerator\MicroFramework\Handler\Trait\RequestMethodGuardTrait; use Iterator; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseInterface; +use Psr\Http\Message\ServerRequestInterface; use test\unit\AssertResponse; final class RequestMethodGuardTraitTest extends TestCase @@ -35,7 +35,7 @@ public static function provider_matching_methods(): Iterator public function testItReturnsNullWhenMethodMatchesAllowedMethod(string $requestMethod, array $allowedMethods): void { $subject = $this->newSubject(); - $request = new ServerRequest($requestMethod, '/'); + $request = $this->newRequest($requestMethod); $this->assertNull($subject->guardRequestMethod($request, ...$allowedMethods)); } @@ -63,7 +63,7 @@ public function testItReturns405ResponseWhenRequestMethodNotAllowed( array $allowedMethods, string $expectAllowHeader, ): void { - $request = new ServerRequest($requestMethod, '/'); + $request = $this->newRequest($requestMethod); $response = $this->newSubject()->guardRequestMethod($request, ...$allowedMethods); @@ -76,6 +76,14 @@ public function testItReturns405ResponseWhenRequestMethodNotAllowed( ); } + 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();