plugins = $plugins; $this->clientCallable = $clientCallable; $this->maxRestarts = (int) ($options['max_restarts'] ?? 0); } private function createChain(): callable { $lastCallable = $this->clientCallable; $reversedPlugins = array_reverse($this->plugins); foreach ($reversedPlugins as $plugin) { $lastCallable = function (RequestInterface $request) use ($plugin, $lastCallable) { return $plugin->handleRequest($request, $lastCallable, $this); }; } return $lastCallable; } public function __invoke(RequestInterface $request): Promise { if ($this->restarts > $this->maxRestarts) { throw new LoopException('Too many restarts in plugin client', $request); } ++$this->restarts; return $this->createChain()($request); } }