This commit is contained in:
2021-09-18 10:38:38 +08:00
parent d0e9f834d4
commit 1f34eb6675
7 changed files with 125 additions and 78 deletions
+35 -1
View File
@@ -3,9 +3,14 @@
namespace Http\Handler;
use Exception;
use Kiri\Core\Help;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
/**
*
*/
class Dispatcher extends \Http\Handler\Abstracts\Handler
{
@@ -17,6 +22,35 @@ class Dispatcher extends \Http\Handler\Abstracts\Handler
*/
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->execute($request);
$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;
}
}