Skip to content

Instantly share code, notes, and snippets.

@lav45
Created January 17, 2026 06:50
Show Gist options
  • Select an option

  • Save lav45/0f99b325a58b38c6f80e3d23b0e279e8 to your computer and use it in GitHub Desktop.

Select an option

Save lav45/0f99b325a58b38c6f80e3d23b0e279e8 to your computer and use it in GitHub Desktop.
<?php declare(strict_types=1);
namespace Webhook\App\Api\Public\Controller;
use Amp\Http\HttpStatus;
use Amp\Http\Server\Request as HttpRequest;
use Amp\Http\Server\Response as HttpResponse;
use Webhook\App\Api\Public\Controller\Request as AppRequest;
use Webhook\App\Http\Server\Request as RequestAdaptor;
use Webhook\App\HttpException;
final readonly class RequestMiddleware
{
public function __invoke(HttpRequest $request, callable $next): HttpResponse
{
$requestAdaptor = new RequestAdaptor($request);
try {
$data = $requestAdaptor->getData();
} catch (\Throwable $exception) {
throw new HttpException(code: HttpStatus::BAD_REQUEST, previous: $exception);
}
$appRequest = new AppRequest(
clientId: $request->getAttribute('clientId'),
urlParams: $request->getAttribute('urlParams'),
query: $requestAdaptor->getQuery(),
data: $data,
headers: $requestAdaptor->getHeaders(),
);
/** @var Response $appResponse */
$appResponse = $next($appRequest);
$headers = $appResponse->headers;
$body = $appResponse->body;
if (\is_array($body)) {
$body = \json_encode($body, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
$headers['content-type'] = 'application/json';
}
return new HttpResponse(
status: $appResponse->status,
headers: $headers,
body: $body,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment