Client.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace App\Libraries\BIM\BlackHole;
  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. $this->client = new \GuzzleHttp\Client([
  11. 'base_uri' => config("bim.black_hole.host"),
  12. 'http_errors' => false,
  13. 'debug' => false,
  14. 'headers' => [
  15. 'Accept' => "application/json",
  16. 'ClientId' => config("bim.black_hole.client_id"),
  17. 'SecretKey' => config("bim.black_hole.secret_key"),
  18. 'UserId' => config("bim.black_hole.user_id"),
  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. protected function parseResponse(ResponseInterface $response): ?array
  37. {
  38. $body = json_decode((string)$response->getBody(), true);
  39. return match ($response->getStatusCode()) {
  40. 200, 201, 204 => $this->parseStatusSuccessResponse($body),
  41. default => throw new FailedException($body['message'] ?? $response->getReasonPhrase()),
  42. };
  43. }
  44. protected function parseStatusSuccessResponse(array $body)
  45. {
  46. $isJson = json_last_error() == JSON_ERROR_NONE;
  47. if (! $isJson) {
  48. return [];
  49. }
  50. if (! $body['isSuccess']) {
  51. throw new FailedException($body['errMsg']);
  52. }
  53. return $body;
  54. }
  55. }