This commit is contained in:
xl
2023-11-22 10:35:50 +08:00
parent 576e1c3ad8
commit 95b0822822
3 changed files with 41 additions and 5 deletions
+22 -5
View File
@@ -2,13 +2,22 @@
namespace Kiri\Router\Format; namespace Kiri\Router\Format;
use Kiri\Di\Inject\Container;
use Kiri\Router\Constrict\Stream; use Kiri\Router\Constrict\Stream;
use Kiri\Router\ContentType;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
class NoBody implements IFormat class NoBody implements IFormat
{ {
/**
* @var ResponseInterface
*/
#[Container(ResponseInterface::class)]
public ResponseInterface $response;
/** /**
* @param $result * @param $result
* @return ResponseInterface * @return ResponseInterface
@@ -16,11 +25,19 @@ class NoBody implements IFormat
public function call($result): ResponseInterface public function call($result): ResponseInterface
{ {
// TODO: Implement call() method. // TODO: Implement call() method.
if ($result instanceof ResponseInterface) { if (request()->getMethod() === 'HEAD') {
$result->getBody()->write(''); return $this->response->withBody(new Stream());
} else { }
$result = 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;
} }
} }
+18
View File
@@ -29,6 +29,9 @@ class Handler implements RequestHandlerInterface
protected mixed $format; protected mixed $format;
protected array $methods = [];
/** /**
* @var ContainerInterface * @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 * @return bool
*/ */
+1
View File
@@ -146,6 +146,7 @@ class RouterCollector implements \ArrayAccess, \IteratorAggregate
if ($value instanceof RequestMethod) { if ($value instanceof RequestMethod) {
$value = $value->getString(); $value = $value->getString();
} }
$handler->setRequestMethod($value);
if (is_array($closure)) { if (is_array($closure)) {
$closure[0] = is_object($closure[0]) ? get_class($closure[0]) : $closure; $closure[0] = is_object($closure[0]) ? get_class($closure[0]) : $closure;
} else if (is_string($closure)) { } else if (is_string($closure)) {