swooleResponse = $swooleResponse; } /** * @param bool $throw * @return string * @author 等风来 * @email 136327134@qq.com * @date 2024/1/25 */ public function getContent(bool $throw = true): string { if ($throw) { $this->checkStatusCode(); } return $this->swooleResponse->getBody(); } /** * @return int * @author 等风来 * @email 136327134@qq.com * @date 2024/1/25 */ public function getStatusCode(): int { return $this->swooleResponse->getStatusCode(); } /** * @param bool $throw * @return array * @author 等风来 * @email 136327134@qq.com * @date 2024/1/25 */ public function getHeaders(bool $throw = true): array { if ($throw) { $this->checkStatusCode(); } $headers = []; foreach ($this->swooleResponse->getHeaders() as $name => $value) { $headers[strtolower($name)][] = $value; } return $headers; } /** * @param bool $throw * @return array * @author 等风来 * @email 136327134@qq.com * @date 2024/1/25 */ public function toArray(bool $throw = true): array { $content = $this->getContent($throw); if ($content === '' && $throw) { throw new \InvalidArgumentException('The content is not valid JSON.'); } return json_decode($content, true); } /** * @author 等风来 * @email 136327134@qq.com * @date 2024/1/25 */ public function cancel(): void { $this->swooleResponse->close(); } /** * @param string|null $type * @return mixed * @author 等风来 * @email 136327134@qq.com * @date 2024/1/24 */ public function getInfo(string $type = null): mixed { if ($type === null || $type === 'http_code') { return $this->getStatusCode(); } $httpResponse = [ 'http_code' => $this->getStatusCode(), 'response_headers' => $this->swooleResponse->getHeaders(), 'url' => $this->swooleResponse->host, ]; return $type ? $httpResponse[$type] ?? null : $httpResponse; } /** * @author 等风来 * @email 136327134@qq.com * @date 2024/1/25 */ private function checkStatusCode() { $code = $this->getInfo('http_code'); if (500 <= $code) { throw new ServerException($this); } if (400 <= $code) { throw new ClientException($this); } if (300 <= $code) { throw new RedirectionException($this); } } }