Files
kiri-core/http-handler/Abstracts/Handler.php
T

100 lines
2.4 KiB
PHP
Raw Normal View History

2021-09-17 18:55:08 +08:00
<?php
namespace Http\Handler\Abstracts;
2021-09-18 10:38:38 +08:00
use Http\Handler\Handler as CHl;
2021-09-18 11:20:58 +08:00
use Kiri\Core\Help;
2021-09-18 10:38:38 +08:00
use Kiri\Kiri;
2021-09-17 18:55:08 +08:00
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
abstract class Handler implements RequestHandlerInterface
{
private int $offset = 0;
/**
* @param CHl $handler
* @param array|null $middlewares
*/
public function __construct(protected CHl $handler, protected ?array $middlewares)
{
}
/**
* @param ServerRequestInterface $request
* @return ResponseInterface
* @throws \Exception
*/
protected function execute(ServerRequestInterface $request): ResponseInterface
{
if (empty($this->middlewares) || !isset($this->middlewares[$this->offset])) {
2021-09-18 10:50:59 +08:00
return $this->dispatcher();
2021-09-17 18:55:08 +08:00
}
$middleware = $this->middlewares[$this->offset];
if (!($middleware instanceof MiddlewareInterface)) {
throw new \Exception('get_implements_class($middleware) not found method process.');
}
++$this->offset;
return $middleware->process($request, $this);
}
2021-09-18 10:50:59 +08:00
/**
* @return mixed
2021-09-18 11:20:58 +08:00
* @throws \Exception
2021-09-18 10:50:59 +08:00
*/
protected function dispatcher(): mixed
{
if ($this->handler->callback instanceof \Closure) {
2021-09-18 11:23:10 +08:00
$response = call_user_func($this->handler->callback, ...$this->handler->params);
} else {
[$controller, $action] = $this->handler->callback;
2021-09-18 10:50:59 +08:00
2021-09-18 11:23:10 +08:00
$controller = Kiri::getDi()->get($controller);
2021-09-18 10:50:59 +08:00
2021-09-18 11:23:10 +08:00
$response = call_user_func([$controller, $action], ...$this->handler->params);
}
2021-09-18 11:21:45 +08:00
if (!($response instanceof ResponseInterface)) {
2021-09-18 11:20:58 +08:00
$response = $this->transferToResponse($response);
}
return $response;
}
/**
* @param mixed $responseData
* @return \Server\Constrict\ResponseInterface
* @throws \Exception
*/
private function transferToResponse(mixed $responseData): ResponseInterface
{
$interface = response()->withStatus(200);
if (!$interface->hasContentType()) {
$interface->withContentType('application/json;charset=utf-8');
}
if (is_object($responseData)) {
$responseData = get_object_vars($responseData);
}
if ($interface->getContentType() == 'application/xml;charset=utf-8') {
$interface->getBody()->write(Help::toXml($responseData));
} else if (is_array($responseData)) {
$interface->getBody()->write(json_encode($responseData));
} else {
$interface->getBody()->write((string)$responseData);
}
return $interface;
2021-09-18 10:50:59 +08:00
}
2021-09-17 18:55:08 +08:00
}