|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Yabacon\Paystack\Http; |
|
4
|
|
|
|
|
5
|
|
|
use \Yabacon\Paystack\Exception\ApiException; |
|
6
|
|
|
|
|
7
|
|
|
class Response |
|
8
|
|
|
{ |
|
9
|
|
|
public $okay; |
|
10
|
|
|
public $body; |
|
11
|
|
|
public $forApi; |
|
12
|
|
|
public $messages = []; |
|
13
|
|
|
|
|
14
|
|
|
private $requestObject; |
|
15
|
|
|
|
|
16
|
9 |
|
public function setRequestObject($requestObject) |
|
17
|
|
|
{ |
|
18
|
9 |
|
$this->requestObject = $requestObject; |
|
19
|
9 |
|
} |
|
20
|
|
|
|
|
21
|
|
|
public function getRequestObject() |
|
22
|
|
|
{ |
|
23
|
|
|
return $this->requestObject; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
6 |
|
private function parsePaystackResponse() |
|
27
|
|
|
{ |
|
28
|
6 |
|
$resp = \json_decode($this->body); |
|
29
|
|
|
|
|
30
|
6 |
|
if ($resp === null || !property_exists($resp, 'status') || !$resp->status) { |
|
31
|
5 |
|
throw new ApiException( |
|
32
|
|
|
"Paystack Request failed with response: '" . |
|
33
|
5 |
|
$this->messageFromApiJson($resp)."'", |
|
34
|
5 |
|
$resp, |
|
35
|
5 |
|
$this->requestObject |
|
36
|
5 |
|
); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
1 |
|
return $resp; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
5 |
|
private function messageFromApiJson($resp) |
|
43
|
|
|
{ |
|
44
|
5 |
|
$message = $this->body; |
|
45
|
5 |
|
if ($resp !== null) { |
|
46
|
4 |
|
if (property_exists($resp, 'message')) { |
|
47
|
3 |
|
$message = $resp->message; |
|
48
|
3 |
|
} |
|
49
|
4 |
|
if (property_exists($resp, 'errors') && ($resp->errors instanceof \stdClass)) { |
|
50
|
1 |
|
$message .= "\nErrors:\n"; |
|
51
|
1 |
|
foreach ($resp->errors as $field => $errors) { |
|
52
|
1 |
|
$message .= "\t" . $field . ":\n"; |
|
53
|
1 |
|
foreach ($errors as $_unused => $error) { |
|
54
|
1 |
|
$message .= "\t\t" . $error->rule . ": "; |
|
55
|
1 |
|
$message .= $error->message . "\n"; |
|
56
|
1 |
|
} |
|
57
|
1 |
|
} |
|
58
|
1 |
|
} |
|
59
|
4 |
|
} |
|
60
|
5 |
|
return $message; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
2 |
|
private function implodedMessages() |
|
64
|
|
|
{ |
|
65
|
2 |
|
return implode("\n\n", $this->messages); |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
9 |
|
public function wrapUp() |
|
69
|
|
|
{ |
|
70
|
9 |
|
if ($this->okay && $this->forApi) { |
|
71
|
6 |
|
return $this->parsePaystackResponse(); |
|
72
|
|
|
} |
|
73
|
3 |
|
if (!$this->okay && $this->forApi) { |
|
74
|
1 |
|
throw new \Exception($this->implodedMessages()); |
|
75
|
|
|
} |
|
76
|
2 |
|
if ($this->okay) { |
|
77
|
1 |
|
return $this->body; |
|
78
|
|
|
} |
|
79
|
1 |
|
error_log($this->implodedMessages()); |
|
80
|
1 |
|
return false; |
|
81
|
|
|
} |
|
82
|
|
|
} |
|
83
|
|
|
|