Passed
Pull Request — master (#20)
by Mathieu
14:57 queued 10:09
created

Curl::getResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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