Completed
Push — master ( 890e48...201e88 )
by Ibrahim
02:37
created

Request::attemptGuzzle()   D

Complexity

Conditions 17
Paths 11

Size

Total Lines 42
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 222.0436

Importance

Changes 0
Metric Value
dl 0
loc 42
ccs 4
cts 37
cp 0.1081
rs 4.9807
c 0
b 0
f 0
cc 17
eloc 32
nc 11
nop 0
crap 222.0436

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Yabacon\Paystack\Http;
4
5
use \Yabacon\Paystack\Contracts\RouteInterface;
6
7
class Request
8
{
9
    public $method;
10
    public $endpoint;
11
    public $body = '';
12
    public $headers = [];
13
    protected $response;
14
    protected $paystackObj;
15
16 7
    public function __construct($paystackObj = null)
17
    {
18 7
        $this->response = new Response();
19 7
        $this->paystackObj = $paystackObj;
20 7
        $this->response->forApi = !is_null($paystackObj);
21 7
        if ($this->response->forApi) {
22 3
            $this->headers['Content-Type'] = 'application/json';
23 3
        }
24 7
    }
25
26
    public function getResponse()
27
    {
28
        return $this->response;
29
    }
30
31 1
    protected function flattenedHeaders()
32
    {
33 1
        $_ = [];
34 1
        foreach ($this->headers as $key => $value) {
35 1
            $_[] = $key . ": " . $value;
36 1
        }
37 1
        return $_;
38
    }
39
40 1
    public function send()
41
    {
42 1
        $this->attemptGuzzle();
43 1
        if (!$this->response->okay) {
44 1
            $this->attemptCurl();
45 1
        }
46 1
        if (!$this->response->okay) {
47 1
            $this->attemptFileGetContents();
48
        }
49
        return $this->response;
50
    }
51
52 1
    public function attemptGuzzle()
53
    {
54 1
        if (!isset($this->paystackObj) || !$this->paystackObj->use_guzzle) {
55 1
            $this->response->okay = false;
56 1
            return;
57
        }
58
        if (class_exists('\\GuzzleHttp\\Exception\\BadResponseException')
59
            && class_exists('\\GuzzleHttp\\Exception\\ClientException')
60
            && class_exists('\\GuzzleHttp\\Exception\\ConnectException')
61
            && class_exists('\\GuzzleHttp\\Exception\\RequestException')
62
            && class_exists('\\GuzzleHttp\\Exception\\ServerException')
63
            && class_exists('\\GuzzleHttp\\Client')
64
            && class_exists('\\GuzzleHttp\\Psr7\\Request')
65
        ) {
66
            $request = new \GuzzleHttp\Psr7\Request(
67
                strtoupper($this->method),
68
                $this->endpoint,
69
                $this->headers,
70
                $this->body
71
            );
72
            $client = new \GuzzleHttp\Client();
73
            try {
74
                $psr7response = $client->send($request);
75
                $this->response->body = $psr7response->getBody()->getContents();
76
                $this->response->okay = true;
77
            } catch (\Exception $e) {
78
                if ($e->hasResponse()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Exception as the method hasResponse() does only exist in the following sub-classes of Exception: GuzzleHttp\Exception\BadResponseException, GuzzleHttp\Exception\ClientException, GuzzleHttp\Exception\ConnectException, GuzzleHttp\Exception\RequestException, GuzzleHttp\Exception\ServerException, GuzzleHttp\Exception\TooManyRedirectsException. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
79
                    $psr7response = $e->getResponse();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Exception as the method getResponse() does only exist in the following sub-classes of Exception: GuzzleHttp\Exception\BadResponseException, GuzzleHttp\Exception\ClientException, GuzzleHttp\Exception\ConnectException, GuzzleHttp\Exception\RequestException, GuzzleHttp\Exception\ServerException, GuzzleHttp\Exception\TooManyRedirectsException, Guzzle\Http\Exception\BadResponseException, Guzzle\Http\Exception\ClientErrorResponseException, Guzzle\Http\Exception\ServerErrorResponseException, Guzzle\Http\Exception\TooManyRedirectsException. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
80
                    $this->response->body = $psr7response->getBody()->getContents();
81
                }
82
                if (($e instanceof \GuzzleHttp\Exception\BadResponseException
83
                    || $e instanceof \GuzzleHttp\Exception\ClientException
84
                    || $e instanceof \GuzzleHttp\Exception\ConnectException
85
                    || $e instanceof \GuzzleHttp\Exception\RequestException
86
                    || $e instanceof \GuzzleHttp\Exception\ServerException)
87
                ) {
88
                    $this->response->okay = true;
89
                }
90
                $this->response->messages[] = $e->getMessage();
91
            }
92
        }
93
    }
94
95 1
    public function attemptFileGetContents()
96
    {
97 1
        $context = stream_context_create(
98
            [
99
                'http'=>array(
100 1
                  'method'=>$this->method,
101 1
                  'header'=>$this->flattenedHeaders(),
102 1
                  'content'=>$this->body,
103
                  'ignore_errors' => true
104 1
                )
105 1
            ]
106 1
        );
107 1
        $this->response->body = file_get_contents($this->endpoint, false, $context);
108
        if ($this->response->body === false) {
109
            $this->response->messages[] = 'file_get_contents failed with response: \'' . error_get_last() . '\'.';
110
        } else {
111
            $this->response->okay = true;
112
        }
113
    }
114
115 1
    public function attemptCurl()
116
    {
117
        //open connection
118 1
        $ch = \curl_init();
119 1
        \curl_setopt($ch, \CURLOPT_URL, $this->endpoint);
120 1
        ($this->method === RouteInterface::POST_METHOD) && \curl_setopt($ch, \CURLOPT_POST, true);
121 1
        ($this->method === RouteInterface::PUT_METHOD) && \curl_setopt($ch, \CURLOPT_CUSTOMREQUEST, 'PUT');
122
123 1
        if ($this->method !== RouteInterface::GET_METHOD) {
124 1
            \curl_setopt($ch, \CURLOPT_POSTFIELDS, $this->body);
125 1
        }
126 1
        \curl_setopt($ch, \CURLOPT_HTTPHEADER, $this->flattenedHeaders());
127 1
        \curl_setopt($ch, \CURLOPT_RETURNTRANSFER, 1);
128 1
        $this->response->forApi && \curl_setopt($ch, \CURLOPT_SSLVERSION, 6);
129
130 1
        $this->response->body = \curl_exec($ch);
131
132 1
        if (\curl_errno($ch)) {
133 1
            $cerr = \curl_error($ch);
134 1
            $this->response->messages[] = 'Curl failed with response: \'' . $cerr . '\'.';
135 1
        } else {
136
            $this->response->okay = true;
137
        }
138
139 1
        \curl_close($ch);
140 1
    }
141
}
142