ConsulResponse.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Consul;
  12. use Hyperf\Collection\Arr;
  13. use Hyperf\Consul\Exception\ServerException;
  14. use Psr\Http\Message\ResponseInterface;
  15. use Psr\Http\Message\StreamInterface;
  16. /**
  17. * @method int getStatusCode()
  18. * @method string getReasonPhrase()
  19. * @method StreamInterface getBody()
  20. */
  21. class ConsulResponse
  22. {
  23. public function __construct(private ResponseInterface $response)
  24. {
  25. }
  26. public function __call($name, $arguments)
  27. {
  28. return $this->response->{$name}(...$arguments);
  29. }
  30. public function json(?string $key = null, $default = null)
  31. {
  32. if ($this->response->getHeaderLine('content-type') !== 'application/json') {
  33. throw new ServerException('The Content-Type of response is not equal application/json');
  34. }
  35. $data = json_decode((string) $this->response->getBody(), true);
  36. if (! $key) {
  37. return $data;
  38. }
  39. return Arr::get($data, $key, $default);
  40. }
  41. }