Client.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace App\Services\File\BIM\BlackHole;
  3. use App\Services\File\BIM\Exceptions\FailedException;
  4. use Psr\Http\Message\ResponseInterface;
  5. class Client {
  6. protected static ?Client $instance = null;
  7. protected \GuzzleHttp\Client $client;
  8. protected function __construct()
  9. {
  10. $this->client = new \GuzzleHttp\Client([
  11. 'base_uri' => config("bim.black_hole.host"),
  12. 'http_errors' => false,
  13. 'headers' => [
  14. 'Accept' => "application/json",
  15. 'ClientId' => config("bim.black_hole.client_id"),
  16. 'SecretKey' => config("bim.black_hole.secret_key"),
  17. 'UserId' => config("bim.black_hole.user_id"),
  18. ]
  19. ]);
  20. }
  21. public static function getInstance(): Client
  22. {
  23. if (! self::$instance) {
  24. self::$instance = new self();
  25. }
  26. return self::$instance;
  27. }
  28. public function request(string $method, string $uri, array $option = []): ?array
  29. {
  30. return $this->parseResponse($this->client->request($method, $uri, $option));
  31. }
  32. protected function parseResponse(ResponseInterface $response): ?array
  33. {
  34. $body = json_decode((string)$response->getBody(), true);
  35. dump((string)$response->getBody());
  36. $isJson = json_last_error() == JSON_ERROR_NONE;
  37. return match ($response->getStatusCode()) {
  38. 200, 201, 204 => $isJson ? $body : null,
  39. default => throw new FailedException($body['message'] ?? $response->getReasonPhrase()),
  40. };
  41. }
  42. }