Client.php 2.2 KB

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