ldc-bogt/app/Lib/CafelApi/Transport/Response.php

136 lines
3.4 KiB
PHP

<?php
namespace App\Lib\CafelApi\Transport;
use App\Enums\ApiStatus;
use App\Exceptions\CafelApiException;
use Psr\Http\Message\ResponseInterface;
/**
* @property int $httpCode The http response code
* @property string $message The api message
* @property array $headers The http reponse headers
* @property array $body The http response body, this is parsed json
* @property ?array $data The reponse data
*
*/
class Response
{
/**
* The response http code
*
* @var integer
*/
private $httpCode = 0;
/**
* The response headers
*
* @var string
*/
private $headers;
/**
* The response body
*
* @var string
*/
private $body;
/**
* The interface message
*
* @var string
*/
private $message;
/**
* PSR response
*
* @var \Psr\Http\Message\ResponseInterface
*/
private $response;
/**
* Response
*
* @param \App\Enums\ApiStatus $status
* @param \Psr\Http\Message\ResponseInterface $response
* @param \App\Lib\CafelApi\Transport\Request $request
* @throws \App\Exceptions\CafelApiException If HTTP response body in not JSON.
*/
public function __construct(ApiStatus $status, ResponseInterface $response, Request $request)
{
$this->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;
}
}