|
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
|
6 |
|
private function parsePaystackResponse() |
|
15
|
|
|
{ |
|
16
|
6 |
|
$resp = \json_decode($this->body); |
|
17
|
|
|
|
|
18
|
6 |
|
if (json_last_error() !== JSON_ERROR_NONE || !property_exists($resp, 'status') || !$resp->status) { |
|
19
|
5 |
|
throw new ApiException( |
|
20
|
|
|
"Paystack Request failed with response: '" . |
|
21
|
5 |
|
$this->messageFromApiJson($resp)."'", |
|
22
|
|
|
$resp |
|
23
|
5 |
|
); |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
1 |
|
return $resp; |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
5 |
|
private function messageFromApiJson($resp){ |
|
30
|
5 |
|
$message = $this->body; |
|
31
|
5 |
|
if(json_last_error() === JSON_ERROR_NONE){ |
|
32
|
4 |
|
if(property_exists($resp, 'message')){ |
|
33
|
3 |
|
$message = $resp->message; |
|
34
|
3 |
|
} |
|
35
|
4 |
|
if(property_exists($resp, 'errors') && ($resp->errors instanceof \stdClass)){ |
|
36
|
1 |
|
$message .= "\nErrors:\n"; |
|
37
|
1 |
|
foreach ($resp->errors as $field => $errors) { |
|
|
|
|
|
|
38
|
1 |
|
$message .= "\t" . $field . ":\n"; |
|
39
|
1 |
|
foreach ($errors as $_unused => $error) { |
|
40
|
1 |
|
$message .= "\t\t" . $error->rule . ": "; |
|
41
|
1 |
|
$message .= $error->message . "\n"; |
|
42
|
1 |
|
} |
|
43
|
1 |
|
} |
|
44
|
1 |
|
} |
|
45
|
4 |
|
} |
|
46
|
5 |
|
return $message; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
2 |
|
private function implodedMessages() |
|
50
|
|
|
{ |
|
51
|
2 |
|
return implode("\n\n", $this->messages); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
9 |
|
public function wrapUp() |
|
55
|
|
|
{ |
|
56
|
9 |
|
if ($this->okay && $this->forApi) { |
|
57
|
6 |
|
return $this->parsePaystackResponse(); |
|
58
|
|
|
} |
|
59
|
3 |
|
if (!$this->okay && $this->forApi) { |
|
60
|
1 |
|
throw new \Exception($this->implodedMessages()); |
|
61
|
|
|
} |
|
62
|
2 |
|
if ($this->okay) { |
|
63
|
1 |
|
return $this->body; |
|
64
|
|
|
} |
|
65
|
1 |
|
error_log($this->implodedMessages()); |
|
66
|
1 |
|
return false; |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|