· 5 years ago · Jul 27, 2020, 02:02 PM
1<?php
2
3
4namespace App\Utils\Guzzle;
5
6
7use Psr\Http\Message\ResponseInterface;
8
9class Response
10{
11 /**
12 * @var null|int The HTTP status code response from API.
13 */
14 protected $httpStatusCode;
15 /**
16 * @var array The headers returned from API request.
17 */
18 protected $headers;
19 /**
20 * @var string The raw body of the response from API request.
21 */
22 protected $body;
23
24 /**
25 * @var array The decoded body of the API response.
26 */
27 protected $decodedBody = [];
28
29 public function __construct(ResponseInterface $response)
30 {
31 $this->httpStatusCode = $response->getStatusCode();
32 $this->body = $response->getBody();
33 $this->headers = $response->getHeaders();
34 $this->decodeBody();
35 }
36
37 /**
38 * Converts raw API response to proper decoded response.
39 */
40 public function decodeBody()
41 {
42 $this->decodedBody = json_decode($this->body, true);
43 if ($this->decodedBody === null) {
44 $this->decodedBody = [];
45 parse_str($this->body, $this->decodedBody);
46 }
47 if (!is_array($this->decodedBody)) {
48 $this->decodedBody = [];
49 }
50 }
51
52 /**
53 * Gets the HTTP status code.
54 * Returns NULL if the request was asynchronous since we are not waiting for the response.
55 *
56 * @return null|int
57 */
58 public function getHttpStatusCode()
59 {
60 return $this->httpStatusCode;
61 }
62
63 /**
64 * Return the HTTP headers for this response.
65 *
66 * @return array
67 */
68 public function getHeaders()
69 {
70 return $this->headers;
71 }
72 /**
73 * Return the raw body response.
74 *
75 * @return string
76 */
77 public function getBody()
78 {
79 return $this->body;
80 }
81
82 /**
83 * Return the decoded body response.
84 *
85 * @param null $key
86 * @return array
87 */
88 public function getDecodedBody($key = null)
89 {
90 if($key != null) return $this->decodedBody[$key] ?? null;
91 return $this->decodedBody;
92 }
93}