Client.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace App\Services\File\BIM\Glendale;
  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.glendale.host"),
  12. 'http_errors' => false,
  13. 'debug' => false,
  14. 'headers' => [
  15. 'Accept' => "application/json",
  16. 'Token' => config("bim.glendale.token"),
  17. ]
  18. ]);
  19. }
  20. public static function getInstance(): Client
  21. {
  22. if (! self::$instance) {
  23. self::$instance = new self();
  24. }
  25. return self::$instance;
  26. }
  27. public function request(string $method, string $uri, array $options = []): ?array
  28. {
  29. return $this->parseResponse($this->client->request($method, $uri, $options));
  30. }
  31. public function post(string $uri, array $options = []) {
  32. return $this->request("POST", $uri, $options);
  33. }
  34. public function get(string $uri, array $params = []) {
  35. return $this->request("POST", $uri, [
  36. 'query_params' => $params
  37. ]);
  38. }
  39. protected function parseResponse(ResponseInterface $response): ?array
  40. {
  41. $body = json_decode((string)$response->getBody(), true);
  42. return match ($response->getStatusCode()) {
  43. 200, 201, 204 => $this->parseStatusSuccessResponse($body),
  44. default => throw new FailedException($body['message'] ?? $response->getReasonPhrase()),
  45. };
  46. }
  47. protected function parseStatusSuccessResponse(array $body)
  48. {
  49. $isJson = json_last_error() == JSON_ERROR_NONE;
  50. if (! $isJson) {
  51. return [];
  52. }
  53. if ($body['code'] != 1) {
  54. throw new FailedException($body['codeMsg']);
  55. }
  56. return $body;
  57. }
  58. }