host; if (!preg_match('/(\d{1,3}\.){3}\d{1,3}/', $host)) { $this->withAddedHeader('Host', $host); } $this->withMethod($method) ->coroutine( $path, $this->paramEncode($params) ); } /** * @param string $path * @return $this */ public function withCAInfo(string $path): static { return $this; } /** * @param string $url * @param array|string $data */ private function coroutine(string $url, array|string $data = []): void { try { $this->generate_client($this->host, $this->isSSL); if ($this->client->statusCode < 0) { throw new Exception($this->client->errMsg); } $this->execute($url, $data); } catch (\Throwable $exception) { $this->statusCode = -1; $this->body = json_encode(['code' => 500, 'message' => $exception->getMessage()]); } } /** * @param string $path * @param array|string $data * @return void */ private function execute(string $path, array|string $data): void { $this->client->execute($this->setParams($path, $data)); if (in_array($this->client->getStatusCode(), [502, 404])) { $this->retry($path, $data); } else { $this->statusCode = $this->client->getStatusCode(); $this->body = $this->client->getBody(); $this->setResponseHeader($this->client->headers); } } /** * @param string $path * @param array|string $data * @return void */ private function retry(string $path, array|string $data): void { if (($this->num += 1) <= $this->retryNum) { sleep($this->retryTimeout); $this->execute($path, $data); } else { $this->statusCode = $this->client->statusCode; $this->body = $this->client->errMsg; } } /** * @param string $host * @param bool $isHttps */ private function generate_client(string $host, bool $isHttps): void { if ($isHttps || $this->isSSL) { $this->client = new SwowClient($host, 443, true); } else { $this->client = new SwowClient($host, $this->getPort(), false); } $this->client->set($this->settings()); if (!empty($this->agent)) { $this->withAddedHeader('User-Agent', $this->agent); } $this->client->setHeaders($this->header); $this->client->setMethod(strtoupper($this->method)); } /** * @param string $path * @param mixed $data * @return string */ private function setParams(string $path, mixed $data): string { $content = $this->_data; if (!empty($content)) { $this->client->setData($content); } if ($this->isGet()) { if (!empty($data)) $path .= '?' . $data; } else if (!empty($data)) { $this->client->setData($data); } return $path; } /** * */ public function close(): void { $this->client->close(); } }