Skip to content

Instantly share code, notes, and snippets.

@nezaniel
Created March 12, 2024 14:17
Show Gist options
  • Save nezaniel/fed2d4519923f15f9508e8ca2be7c4d4 to your computer and use it in GitHub Desktop.
Save nezaniel/fed2d4519923f15f9508e8ca2be7c4d4 to your computer and use it in GitHub Desktop.
Http Endpoint
<?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