This commit is contained in:
2021-09-18 11:20:58 +08:00
parent 3389d234d5
commit 7beef23040
2 changed files with 33 additions and 31 deletions
+32 -1
View File
@@ -3,6 +3,7 @@
namespace Http\Handler\Abstracts;
use Http\Handler\Handler as CHl;
use Kiri\Core\Help;
use Kiri\Kiri;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
@@ -50,6 +51,7 @@ abstract class Handler implements RequestHandlerInterface
/**
* @return mixed
* @throws \Exception
*/
protected function dispatcher(): mixed
{
@@ -61,7 +63,36 @@ abstract class Handler implements RequestHandlerInterface
$controller = Kiri::getDi()->get($controller);
return call_user_func([$controller, $action], ...$this->handler->params);
$response = call_user_func([$controller, $action], ...$this->handler->params);
if (!$response instanceof ResponseInterface) {
$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;
}
+1 -30
View File
@@ -22,35 +22,6 @@ class Dispatcher extends \Http\Handler\Abstracts\Handler
*/
public function handle(ServerRequestInterface $request): ResponseInterface
{
$response = $this->execute($request);
if (!$response instanceof ResponseInterface) {
return $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;
return $this->execute($request);
}
}