response = $response; $this->status = $status; $this->httpCode = $response->getStatusCode(); $this->headers = $response->getHeaders(); /** @var \GuzzleHttp\Psr7\Stream */ $this->body = $response->getBody(); if (!in_array($response->getStatusCode(), [200, 201])) { $this->message = $response->getReasonPhrase(); } // * Body should be json data. if (($decodedJson = $this->tryDecodeJson($this->body->getContents())) === false) { if (in_array(config('app.env'), ['testing', 'local'])) { dump( 'should have been json', $this->httpCode, $this->status, $this->headers, $request->uri, (string)$this->body ); } throw new CafelApiException( "The Api should have returned JSON data '{$request->uri}'" ); } $this->body = $decodedJson; // * If Api Error. if ($this->status->equals(ApiStatus::KO())) { new CafelApiException("CAfel Api responded http code $this->httpCode"); } return $this; } /** * Generic accessor * * @param string $field * @return mixed|null */ public function __get(string $field) { if ( \in_array($field, [ 'status', 'httpCode', 'headers', 'body', 'message', 'response' ]) ) { return $this->{$field}; } if ($field === 'data' and isset($this->body[$field])) { return $this->body[$field]; } return null; } /** * Try to decode json and return false if it is * not a valid json * * @param string $string * @return array|false Returns an associative data array or false if failed to parse. */ private function tryDecodeJson(string $string) { /** @var array|null */ $data = json_decode($string, true); return (json_last_error() == JSON_ERROR_NONE) ? $data : false; } }