Created
March 12, 2024 14:17
-
-
Save nezaniel/fed2d4519923f15f9508e8ca2be7c4d4 to your computer and use it in GitHub Desktop.
Http Endpoint
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
use GuzzleHttp\Psr7\Utils; | |
use Psr\Http\Message\ResponseInterface; | |
use Psr\Http\Message\ServerRequestInterface; | |
abstract class HttpEndpoint | |
{ | |
final public function handleRequest(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface | |
{ | |
$requestMethod = strtolower($request->getMethod()); | |
if (!method_exists($this, $requestMethod)) { | |
$responseObject = new MethodNotAllowed(); | |
} else { | |
$parameters = ParameterFactory::resolveParameters(get_class($this), $requestMethod, $request); | |
$responseObject = $this->$requestMethod(...$parameters); | |
} | |
$response = $response->withBody(Utils::streamFor(\json_encode($responseObject, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT))); | |
$responseAttribute = PathResponse::fromReflectionClass(new \ReflectionClass($responseObject)); | |
$response = $response->withStatus($responseAttribute->statusCode); | |
return $response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment