1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace PatricPoba\MtnMomo\Http; |
4
|
|
|
|
5
|
|
|
use PatricPoba\MtnMomo\Utilities\AttributesMassAssignable; |
6
|
|
|
|
7
|
|
|
|
8
|
|
|
class ApiResponse |
9
|
|
|
{ |
10
|
|
|
use AttributesMassAssignable; |
11
|
|
|
|
12
|
|
|
protected $headers; |
13
|
|
|
protected $content; |
14
|
|
|
protected $statusCode; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Construct object |
18
|
|
|
* |
19
|
|
|
* @param int $statusCode |
20
|
|
|
* @param string $content |
21
|
|
|
* @param array $headers |
22
|
|
|
*/ |
23
|
|
|
public function __construct($statusCode, $content, $headers = array()) |
24
|
|
|
{ |
25
|
|
|
$this->statusCode = $statusCode; |
26
|
|
|
$this->headers = $headers; |
27
|
|
|
$this->content = $content; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Dynamically create class variables from content array, so content can be accessed directly. |
31
|
|
|
* eg $response->category, $response->user_id for ['category'=> 'Electronics','user_id'=> 4] |
32
|
|
|
* $this->content must be set before calling $this->massAssignAttributes() |
33
|
|
|
*/ |
34
|
|
|
$this->massAssignAttributes($this->toArray()); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Get array format of api response |
39
|
|
|
* @return array |
40
|
|
|
*/ |
41
|
|
|
public function toArray() : array |
42
|
|
|
{ |
43
|
|
|
return \json_decode($this->content, true); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Get json format of api response |
48
|
|
|
* @return string |
49
|
|
|
*/ |
50
|
|
|
public function toJson() : string |
51
|
|
|
{ |
52
|
|
|
return $this->content; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Get the status code of the response |
57
|
|
|
* @return numeric |
58
|
|
|
*/ |
59
|
|
|
public function getStatusCode() : int |
60
|
|
|
{ |
61
|
|
|
return $this->statusCode; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
public function getHeaders() |
65
|
|
|
{ |
66
|
|
|
return $this->headers; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* Checks if api call was successful ie 200, 201 etc |
71
|
|
|
* return bool |
72
|
|
|
*/ |
73
|
|
|
public function isSuccess() : bool |
74
|
|
|
{ |
75
|
|
|
return $this->getStatusCode() < 400; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
|
79
|
|
|
public function __toString() |
80
|
|
|
{ |
81
|
|
|
return '[Response] HTTP ' . $this->getStatusCode() . ' ' . $this->content; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|