format = Kiri::getDi()->get($parameter); } else { $this->format = Kiri::getDi()->get(MixedFormat::class); } } /** * @param string $method * @return void * @throws */ public function setRequestMethod(string $method): void { if ($method == 'HEAD' || $method == 'OPTIONS') { $this->format = Kiri::getDi()->get(NoBody::class); } } /** * @return bool */ public function isClosure(): bool { return $this->handler instanceof Closure; } /** * @param string $interface * @return bool */ public function implement(string $interface): bool { if (!$this->handler instanceof Closure) { return $this->handler[0] instanceof $interface; } return false; } /** * @return string|null */ public function getClass(): ?string { if ($this->handler instanceof Closure) { return null; } return $this->handler[0]; } /** * @return string|null */ public function getMethod(): ?string { if ($this->handler instanceof Closure) { return null; } return $this->handler[1]; } /** * @param array $middlewares * @return void */ public function setMiddlewares(array $middlewares): void { $this->middlewares = $middlewares; } /** * @return array */ public function getMiddlewares(): array { return $this->middlewares; } public function setSourceFile(?string $sourceFile): void { $this->sourceFile = $sourceFile; } public function getSourceFile(): ?string { return $this->sourceFile; } public function setSourceKind(string $sourceKind): void { $this->sourceKind = $sourceKind; } public function getSourceKind(): string { return $this->sourceKind; } /** * @param Defer[] $deferred * @return void */ public function setDeferred(array $deferred): void { $this->deferred = $deferred; } /** * @return Defer[] */ public function getDeferred(): array { return $this->deferred; } /** * @param ServerRequestInterface $request * @return ResponseInterface * @throws */ public function handle(ServerRequestInterface $request): ResponseInterface { $controller = Kiri::getDi()->get($this->handler[0]); $data = call_user_func([$controller, $this->handler[1]], ...$this->parameters); $this->executeDeferred(); /** 根据返回类型 */ return $this->format->call($data); } /** * @return void */ private function executeDeferred(): void { foreach ($this->deferred as $defer) { try { $callback = $defer->callback; $params = $defer->params; if (is_array($callback)) { [$class, $method] = $callback; $instance = Kiri::getDi()->get($class); call_user_func([$instance, $method], ...$params); } else { $instance = Kiri::getDi()->get($callback); call_user_func([$instance, '__invoke'], ...$params); } } catch (\Throwable $throwable) { \Kiri::getLogger()->error('Defer callback failed: ' . $throwable->getMessage()); } } } }