Curl::send()   B
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 51
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 6
eloc 30
c 2
b 0
f 0
nc 6
nop 0
dl 0
loc 51
ccs 0
cts 29
cp 0
crap 42
rs 8.8177

How to fix   Long Method   

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
declare(strict_types=1);
4
5
namespace Suricate;
6
7
use Exception;
8
9
/**
10
 * Curl extension for Suricate
11
 *
12
 * @package Suricate
13
 * @author  Mathieu LESNIAK <[email protected]>
14
 *
15
 * @property string $userAgent
16
 * @property int $timeout
17
 * @property int $connectTimeout
18
 * @property string $proxyHost
19
 * @property int $proxyPort
20
 * @property string $referer
21
 * @property string $cookie
22
 * @property string $userAgent
23
 * @property mixed $postFields
24
 * @property string $login
25
 * @property string $password
26
 * @property array $headers
27
 */
28
29
class Curl extends Service
30
{
31
    protected $parametersList = [
32
        'userAgent',
33
        'timeout',
34
        'connectTimeout',
35
        'proxyHost',
36
        'proxyPort',
37
        'referer',
38
        'cookie',
39
        'userAgent',
40
        'postFields',
41
        'login',
42
        'password',
43
        'headers'
44
    ];
45
46
    private $request;
47
    private $response;
48
    private $responseData;
49
    private $errorMsg;
50 1
    private $errorCode;
51
52 1
    public function __construct()
53
    {
54 1
        parent::__construct();
55 1
56 1
        $this->request = new Request();
57 1
        $this->response = new Request();
58
        $this->headers = [];
59 1
    }
60
61 1
    public function setUrl($url)
62
    {
63 1
        $this->request->setUrl($url);
64
65
        return $this;
66 1
    }
67
68 1
    public function getUrl()
69
    {
70
        return $this->request->getUrl();
71 1
    }
72
73 1
    public function setMethod($method)
74
    {
75 1
        $this->request->setMethod($method);
76
77
        return $this;
78 1
    }
79
80 1
    public function setUserAgent($userAgent)
81
    {
82 1
        $this->userAgent = $userAgent;
83
84
        return $this;
85 1
    }
86
87 1
    public function addHeader($headerLine)
88 1
    {
89
        $headers = $this->headers;
90 1
        $headers[] = $headerLine;
91
92 1
        $this->headers = $headers;
93
94
        return $this;
95
    }
96
97
    /**
98
     * @SuppressWarnings(PHPMD.UndefinedVariable) : preg_match_all matches
99
     */
100
    public function send()
101
    {
102
        $curlHandler = curl_init($this->request->getUrl());
103
104
        if ($curlHandler === false) {
105
            throw new Exception("Can't init curl");
106
        }
107
        $curlOptions = $this->generateCurlOptions();
108
        curl_setopt_array($curlHandler, $curlOptions);
109
110
        $curlResponse = curl_exec($curlHandler);
111
        if ($curlResponse === false) {
112
            $this->errorMsg = curl_error($curlHandler);
113
            $this->errorCode = curl_errno($curlHandler);
114
115
            return false;
116
        }
117
        // No return transfer option
118
        if (is_bool($curlResponse)) {
119
            return true;
120
        }
121
122
        $this->responseData = curl_getinfo($curlHandler);
123
        $this->response->setUrl($this->responseData['url']);
124
        $redirectCount = curl_getinfo($curlHandler, CURLINFO_REDIRECT_COUNT);
125
126
        $splittedResponse = explode(
127
            "\r\n\r\n",
128
            $curlResponse,
129
            $redirectCount + 2
130
        );
131
        $lastHeader = $splittedResponse[$redirectCount];
132
133
        // get headers out of response
134
        $headers = explode("\n", trim($lastHeader));
135
        array_shift($headers);
136
137
        foreach ($headers as $headerLine) {
138
            preg_match('|^([\d\w\s_-]*):(.*)|', $headerLine, $matches);
139
            if (isset($matches[1])) {
140
                $this->response->addHeader($matches[1], trim($matches[2]));
141
            }
142
        }
143
144
        // Reponse data
145
        $this->response->setHttpCode($this->responseData['http_code']);
146
        $this->response->setBody(
147
            substr($curlResponse, $this->responseData['header_size'])
148
        );
149
150
        return $this;
151
    }
152
153
    private function generateCurlOptions()
154
    {
155
        $curlOptions = [
156
            CURLOPT_RETURNTRANSFER => true,
157
            CURLOPT_HEADER => true,
158
            CURLINFO_HEADER_OUT => true,
159
            CURLOPT_FOLLOWLOCATION => true,
160
            CURLOPT_SSL_VERIFYPEER => false,
161
            CURLOPT_SSL_VERIFYHOST => false
162
        ];
163
164
        $parametersMapping = [
165
            CURLOPT_CONNECTTIMEOUT => 'connectTimeout',
166
            CURLOPT_TIMEOUT => 'timeout',
167
            CURLOPT_PROXY => 'proxyHost',
168
            CURLOPT_PROXYPORT => 'proxyPort',
169
            CURLOPT_REFERER => 'referer',
170
            CURLOPT_COOKIE => 'cookie',
171
            CURLOPT_USERAGENT => 'userAgent',
172
            CURLOPT_HTTPHEADER => 'headers'
173
        ];
174
175
        foreach ($parametersMapping as $curlKey => $optionKey) {
176
            if (($value = $this->getParameter($optionKey)) !== null) {
177
                $curlOptions[$curlKey] = $value;
178
            }
179
        }
180
181
        //
182
        // Method management
183
        //
184
        if ($this->request->getMethod() == Request::HTTP_METHOD_GET) {
185
            $curlOptions[CURLOPT_HTTPGET] = true;
186
        } elseif ($this->request->getMethod() == Request::HTTP_METHOD_POST) {
187
            $curlOptions[CURLOPT_POST] = true;
188
            if ($this->getParameter('postFields') !== null) {
189
                $curlOptions[CURLOPT_POSTFIELDS] = $this->getParameter(
190
                    'postFields'
191
                );
192
            }
193
        } elseif ($this->request->getMethod() == Request::HTTP_METHOD_PUT) {
194
            $curlOptions[CURLOPT_CUSTOMREQUEST] = "PUT";
195
            if ($this->getParameter('postFields') !== null) {
196
                $curlOptions[CURLOPT_POSTFIELDS] = $this->getParameter(
197
                    'postFields'
198
                );
199
            }
200
        } elseif ($this->request->getMethod() == Request::HTTP_METHOD_HEAD) {
201
            $curlOptions[CURLOPT_NOBODY] = true;
202
        } elseif ($this->request->getMethod() == Request::HTTP_METHOD_DELETE) {
203
            $curlOptions[CURLOPT_CUSTOMREQUEST] = "DELETE";
204
        }
205
206
        return $curlOptions;
207
    }
208
209
    public function getResponse()
210
    {
211
        return $this->response;
212
    }
213
214
    public function getHeaders()
215
    {
216
        return $this->response->getHeaders();
217
    }
218
219
    public function getHttpCode()
220
    {
221
        return isset($this->responseData['http_code'])
222
            ? $this->responseData['http_code']
223
            : null;
224
    }
225
226
    public function getErrorMsg()
227
    {
228
        return $this->errorMsg;
229
    }
230
231
    public function getErrorCode()
232
    {
233
        return $this->errorCode;
234
    }
235
}
236