Client.php 2.1 KB

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