CurlClient::process()   C
last analyzed

Complexity

Conditions 12
Paths 36

Size

Total Lines 70
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 12
eloc 44
c 1
b 1
f 0
nc 36
nop 1
dl 0
loc 70
rs 6.9666

How to fix   Long Method    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 XoopsModules\Wggithub\Github\Http;
4
5
use XoopsModules\Wggithub\Github;
6
7
8
/**
9
 * HTTP client which use the cURL extension functions.
10
 *
11
 * @author  Miloslav Hůla (https://github.com/milo)
12
 */
13
class CurlClient extends AbstractClient
14
{
15
    /** @var array|NULL */
16
    private $options;
17
18
    /** @var resource */
19
    private $curl;
20
21
22
    /**
23
     * @param  array  cURL options {@link http://php.net/manual/en/function.curl-setopt.php}
24
     *
25
     * @throws Github\LogicException
26
     */
27
    public function __construct(array $options = NULL)
28
    {
29
        if (!\extension_loaded('curl')) {
30
            throw new Github\LogicException('cURL extension is not loaded.');
31
        }
32
33
        $this->options = $options;
34
    }
35
36
37
    protected function setupRequest(Request $request)
38
    {
39
        parent::setupRequest($request);
40
        $request->addHeader('Connection', 'keep-alive');
41
    }
42
43
44
    /**
45
     * @param Request $request
46
     * @return Response
47
     *
48
     */
49
    protected function process(Request $request)
50
    {
51
        $headers = [];
52
        foreach ($request->getHeaders() as $name => $value) {
53
            $headers[] = "$name: $value";
54
        }
55
56
        $responseHeaders = [];
57
        $softOptions = [
58
            CURLOPT_CONNECTTIMEOUT => 10,
59
            CURLOPT_SSL_VERIFYHOST => 2,
60
            CURLOPT_SSL_VERIFYPEER => 1,
61
            CURLOPT_CAINFO => realpath(__DIR__ . '/../ca-chain.crt'),
62
        ];
63
64
        $hardOptions = [
65
            CURLOPT_FOLLOWLOCATION => FALSE, # Github sets the Location header for 201 code too and redirection is not required for us
66
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
67
            CURLOPT_CUSTOMREQUEST => $request->getMethod(),
68
            CURLOPT_NOBODY => $request->isMethod(Request::HEAD),
69
            CURLOPT_URL => $request->getUrl(),
70
            CURLOPT_HTTPHEADER => $headers,
71
            CURLOPT_RETURNTRANSFER => TRUE,
72
            CURLOPT_POSTFIELDS => $request->getContent(),
73
            CURLOPT_HEADER => FALSE,
74
            CURLOPT_HEADERFUNCTION => function($curl, $line) use (& $responseHeaders, & $last) {
75
                if (strncasecmp($line, 'HTTP/', 5) === 0) {
76
                    /** @todo Set proxy response as Response::setPrevious($proxyResponse)? */
77
                    # The HTTP/x.y may occur multiple times with proxy (HTTP/1.1 200 Connection Established)
78
                    $responseHeaders = [];
79
80
                } elseif (\in_array(\substr($line, 0, 1), [' ', "\t"], TRUE)) {
81
                    $responseHeaders[$last] .= ' ' . \trim($line);  # RFC2616, 2.2
82
83
                } elseif ($line !== "\r\n") {
84
                    list($name, $value) = \explode(':', $line, 2);
85
                    $responseHeaders[$last = \trim($name)] = \trim($value);
86
                }
87
88
                return \strlen($line);
89
            },
90
        ];
91
92
        if (\defined('CURLOPT_PROTOCOLS')) {  # HHVM issue. Even cURL v7.26.0, constants are missing.
93
            $hardOptions[CURLOPT_PROTOCOLS] = CURLPROTO_HTTP | CURLPROTO_HTTPS;
94
        }
95
96
        if (!$this->curl) {
97
            $this->curl = \curl_init();
0 ignored issues
show
Documentation Bug introduced by
It seems like curl_init() can also be of type CurlHandle. However, the property $curl is declared as type resource. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
98
            if ($this->curl === FALSE) {
99
                throw new BadResponseException('Cannot init cURL handler.');
100
            }
101
        }
102
103
        $result = curl_setopt_array($this->curl, $hardOptions + ($this->options ?: []) + $softOptions);
104
        if ($result === FALSE) {
105
            throw new BadResponseException('Setting cURL options failed: ' . \curl_error($this->curl), curl_errno($this->curl));
106
        }
107
108
        $content = \curl_exec($this->curl);
109
        if ($content === FALSE) {
110
            throw new BadResponseException(\curl_error($this->curl), curl_errno($this->curl));
111
        }
112
113
        $code = \curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
114
        if ($code === FALSE) {
115
            throw new BadResponseException('HTTP status code is missing:' . \curl_error($this->curl), curl_errno($this->curl));
116
        }
117
118
        return new Response($code, $responseHeaders, $content);
119
    }
120
121
}
122