Files
kiri-router/src/OnRequest.php
T
2026-04-17 16:30:52 +08:00

116 lines
3.2 KiB
PHP

<?php
declare(strict_types=1);
namespace Kiri\Router;
use Kiri\Abstracts\CoordinatorManager;
use Kiri\Coordinator;
use Kiri\Di\Inject\Container;
use Kiri\Di\Context;
use Kiri\Di\Interface\ResponseEmitterInterface;
use Kiri\Router\Base\ExceptionHandlerDispatcher;
use Kiri\Router\Constrict\ConstrictRequest as CQ;
use Kiri\Router\Constrict\ConstrictResponse;
use Kiri\Router\Interface\ExceptionHandlerInterface;
use Kiri\Router\Interface\OnRequestInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Throwable;
/**
* OnRequest event
*/
class OnRequest implements OnRequestInterface
{
/**
* @var RouterCollector
*/
public RouterCollector $router;
public DataGrip $dataGrip;
/**
* @var ExceptionHandlerInterface
*/
public ExceptionHandlerInterface $exception;
/**
* @var ResponseEmitterInterface
*/
public ResponseEmitterInterface $responseEmitter;
/**
* @var ConstrictResponse
*/
#[Container(ConstrictResponse::class)]
public ConstrictResponse $constrictResponse;
/**
* @param ResponseInterface $response
* @param DataGrip $dataGrip
*/
public function __construct(public ResponseInterface $response, DataGrip $dataGrip)
{
$this->dataGrip = $dataGrip;
$this->responseEmitter = $this->response->emmit;
$exception = \config('servers.request.exception');
if (!in_array(ExceptionHandlerInterface::class, class_implements($exception))) {
$exception = ExceptionHandlerDispatcher::class;
}
$this->exception = \Kiri::getDi()->get($exception);
$this->router = $dataGrip->get(ROUTER_TYPE_HTTP);
}
/**
* @param Request $request
* @param Response $response
* @throws
*/
public function onRequest(Request $request, Response $response): void
{
try {
$this->setResponseHeaders($response, $this->response->headers);
/** @var CQ $PsrRequest */
Context::set(ResponseInterface::class, new ConstrictResponse($this->response->contentType));
$PsrRequest = Context::set(RequestInterface::class, CQ::builder($request));
$this->router = $this->dataGrip->get(ROUTER_TYPE_HTTP);
CoordinatorManager::utility(Coordinator::WORKER_START)->yield();
$PsrResponse = $this->router->query($request->server['path_info'], $request->getMethod())->run($PsrRequest);
} catch (Throwable $throwable) {
\Kiri::getLogger()->json_log($throwable);
$PsrResponse = $this->exception->emit($throwable, $this->constrictResponse);
} finally {
$this->responseEmitter->response($PsrResponse, $response, $PsrRequest);
}
}
/**
* @param Response $response
* @param array $headers
* @return void
*/
protected function setResponseHeaders(Response $response, array $headers): void
{
foreach ($headers as $key => $header) {
$response->header($key, $header);
}
}
}