Completed
Push — master ( b9561f...67eff5 )
by Ibrahim
06:57
created

Response   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 18
lcom 1
cbo 1
dl 0
loc 62
ccs 36
cts 36
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A parsePaystackResponse() 0 14 4
B messageFromApiJson() 0 19 7
A implodedMessages() 0 4 1
B wrapUp() 0 14 6
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) {
0 ignored issues
show
Bug introduced by
The expression $resp->errors of type object<stdClass> is not traversable.
Loading history...
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