diff --git a/src/Api.php b/src/Api.php index 6d306ed..2e97c4d 100644 --- a/src/Api.php +++ b/src/Api.php @@ -21,7 +21,7 @@ class Api { public function __construct(string $token, ClientInterface $client = null) { $this->token = $token; - $this->client = is_null($client) ? new Client() : $client; + $this->client = $client; } public function getMe(): User { @@ -213,21 +213,11 @@ public function request(string $method, array $params = [], $type = null, $isArr $params['reply_markup'] = (string)$params['reply_markup']; } - try { - $result = $this->client->request('POST', self::API_URL."/bot{$this->token}/{$method}", ['form_params' => $params]); - } catch (ClientException $e) { - if (strpos($e->getMessage(), 'response:') !== false) { - $ex = explode('response:', $e->getMessage()); - $response = json_decode(trim(end($ex))); - - if (empty($response)) { - throw new ResponseException($e->getMessage(), $e->getCode()); - } else { - throw new ResponseException($response->description, $response->error_code); - } - } else { - throw $e; - } + $result = $this->getClient()->post(self::API_URL."/bot{$this->token}/{$method}", ['form_params' => $params]); + $data = json_decode($result->getBody(), true); + + if (!$data['ok']) { + throw new ResponseException($data['description'], $data['error_code']); } $data = json_decode($result->getBody(), true); @@ -239,6 +229,15 @@ public function request(string $method, array $params = [], $type = null, $isArr } else { return is_null($type) ? $data['result'] : new $type($data['result']); } + } + + protected function getClient(): ClientInterface { + if (empty($this->client)) { + $this->client = new Client([ + 'http_errors' => false + ]); + } + return $this->client; } } \ No newline at end of file diff --git a/tests/TestClient.php b/tests/TestClient.php index d00c5f2..2cff3ad 100644 --- a/tests/TestClient.php +++ b/tests/TestClient.php @@ -29,7 +29,7 @@ protected function getMe(array $params) { protected function getChat(array $params) { if ($params['chat_id'] == -1) { - throw new ClientException('`400 Bad Request` response:{"ok":false,"error_code":400,"description":"Bad Request: chat not found"}', new Request('POST', '/')); + return '{"ok":false,"error_code":400,"description":"Bad Request: chat not found"}'; } }