Files
kiri-router/src/Format/NoBody.php
T

43 lines
1.1 KiB
PHP
Raw Normal View History

2023-11-22 10:19:33 +08:00
<?php
namespace Kiri\Router\Format;
2023-11-22 10:35:50 +08:00
use Kiri\Di\Inject\Container;
2023-11-22 10:19:33 +08:00
use Kiri\Router\Constrict\Stream;
2023-11-22 10:35:50 +08:00
use Kiri\Router\ContentType;
2023-11-22 10:19:33 +08:00
use Psr\Http\Message\ResponseInterface;
class NoBody implements IFormat
{
2023-11-22 10:35:50 +08:00
/**
* @var ResponseInterface
*/
#[Container(ResponseInterface::class)]
public ResponseInterface $response;
2023-11-22 10:19:33 +08:00
/**
* @param $result
* @return ResponseInterface
*/
public function call($result): ResponseInterface
{
// TODO: Implement call() method.
2023-11-22 10:35:50 +08:00
if (request()->getMethod() === 'HEAD') {
return $this->response->withBody(new Stream());
}
2023-11-22 10:19:33 +08:00
if ($result instanceof ResponseInterface) {
2023-11-22 10:35:50 +08:00
return $result;
}
if (is_object($result)) {
return $this->response->withBody(new Stream('[object]'));
}
if (is_array($result)) {
return $this->response->withContentType(ContentType::JSON)->withBody(new Stream(json_encode($result, JSON_UNESCAPED_UNICODE)));
2023-11-22 10:19:33 +08:00
} else {
2023-11-22 10:35:50 +08:00
return $this->response->withBody(new Stream((string)$result));
2023-11-22 10:19:33 +08:00
}
}
}