| 1 |
<?php |
| 2 |
|
| 3 |
namespace Metricool\Http\RSPAL; |
| 4 |
|
| 5 |
use Metricool\Vendor\Psr\Http\Message\ResponseInterface; |
| 6 |
use Metricool\Exceptions\RestDataException; |
| 7 |
|
| 8 |
class RspalApiResponse |
| 9 |
{ |
| 10 |
public int $statusCode; |
| 11 |
public object $data; |
| 12 |
|
| 13 |
public function __construct(int $statusCode, object $data) |
| 14 |
{ |
| 15 |
$this->statusCode = $statusCode; |
| 16 |
$this->data = $data; |
| 17 |
} |
| 18 |
|
| 19 |
public static function fromResponse(ResponseInterface $response): self |
| 20 |
{ |
| 21 |
$statusCode = $response->getStatusCode(); |
| 22 |
$body = $response->getBody()->getContents(); |
| 23 |
$data = json_decode($body, false); |
| 24 |
|
| 25 |
if (!is_object($data)) { |
| 26 |
throw new RestDataException('Invalid or empty response from the API'); |
| 27 |
} |
| 28 |
|
| 29 |
if (isset($data->status) && $data->status == 'OK') { |
| 30 |
throw new RestDataException('An error occurred'); |
| 31 |
} |
| 32 |
|
| 33 |
return new self( |
| 34 |
$statusCode, |
| 35 |
$data |
| 36 |
); |
| 37 |
} |
| 38 |
|
| 39 |
public function getStatusCode(): int |
| 40 |
{ |
| 41 |
return $this->statusCode; |
| 42 |
} |
| 43 |
|
| 44 |
public function getData(): object |
| 45 |
{ |
| 46 |
return $this->data; |
| 47 |
} |
| 48 |
} |
| 49 |
|