diff --git a/src/Format/NoBody.php b/src/Format/NoBody.php index 0f609d5..0da7f7f 100644 --- a/src/Format/NoBody.php +++ b/src/Format/NoBody.php @@ -2,13 +2,22 @@ namespace Kiri\Router\Format; +use Kiri\Di\Inject\Container; use Kiri\Router\Constrict\Stream; +use Kiri\Router\ContentType; use Psr\Http\Message\ResponseInterface; class NoBody implements IFormat { + /** + * @var ResponseInterface + */ + #[Container(ResponseInterface::class)] + public ResponseInterface $response; + + /** * @param $result * @return ResponseInterface @@ -16,11 +25,19 @@ class NoBody implements IFormat public function call($result): ResponseInterface { // TODO: Implement call() method. - if ($result instanceof ResponseInterface) { - $result->getBody()->write(''); - } else { - $result = response()->withBody(new Stream()); + if (request()->getMethod() === 'HEAD') { + return $this->response->withBody(new Stream()); + } + if ($result instanceof ResponseInterface) { + 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))); + } else { + return $this->response->withBody(new Stream((string)$result)); } - return $result; } } \ No newline at end of file diff --git a/src/Handler.php b/src/Handler.php index 87da378..bc8a878 100644 --- a/src/Handler.php +++ b/src/Handler.php @@ -29,6 +29,9 @@ class Handler implements RequestHandlerInterface protected mixed $format; + protected array $methods = []; + + /** * @var ContainerInterface */ @@ -69,6 +72,21 @@ class Handler implements RequestHandlerInterface } + /** + * @param string $method + * @return void + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws ReflectionException + */ + public function setRequestMethod(string $method): void + { + if ($method == 'HEAD') { + $this->format = $this->container->get(NoBody::class); + } + } + + /** * @return bool */ diff --git a/src/RouterCollector.php b/src/RouterCollector.php index a633d99..c000427 100644 --- a/src/RouterCollector.php +++ b/src/RouterCollector.php @@ -146,6 +146,7 @@ class RouterCollector implements \ArrayAccess, \IteratorAggregate if ($value instanceof RequestMethod) { $value = $value->getString(); } + $handler->setRequestMethod($value); if (is_array($closure)) { $closure[0] = is_object($closure[0]) ? get_class($closure[0]) : $closure; } else if (is_string($closure)) {