Passed
Push — master ( ede639...ef74f3 )
by Dev
02:20
created

Request::setEncodingGzip()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PiedWeb\Curl;
4
5
class Request
6
{
7
    use UserAgentTrait;
8
9
    /**
10
     * Curl resource handle.
11
     *
12
     * @var resource
13
     */
14
    private $handle;
15
16
    /** @var string contains targeted URL */
17
    private $url;
18
19
    /** @var int */
20
    private $returnHeader = 0;
21
22
    /** @var bool */
23
    private $gzip = false;
24
25
    /** @var mixed */
26
    private $filter;
27
28
    /**
29
     * Constructor.
30
     *
31
     * @param string $ur to request
32
     */
33 5
    public function __construct(?string $url = null)
34
    {
35 5
        $this->handle = curl_init();
36 5
        $this->setOpt(CURLOPT_RETURNTRANSFER, 1);
37
38 5
        $this->setUrl($url);
0 ignored issues
show
Bug introduced by
It seems like $url can also be of type null; however, parameter $url of PiedWeb\Curl\Request::setUrl() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

38
        $this->setUrl(/** @scrutinizer ignore-type */ $url);
Loading history...
39 5
    }
40
41
    /**
42
     * Change the URL to cURL.
43
     *
44
     * @param string $url to request
45
     *
46
     * @return self
47
     */
48 5
    public function setUrl(string $url)
49
    {
50 5
        $this->url = $url;
51 5
        $this->setOpt(CURLOPT_URL, $url);
52
53 5
        return $this;
54
    }
55
56
    /**
57
     * Add a cURL's option.
58
     *
59
     * @param int   $option cURL Predefined Constant
60
     * @param mixed $value
61
     *
62
     * @return self
63
     */
64 5
    public function setOpt($option, $value)
65
    {
66 5
        curl_setopt($this->handle, $option, $value);
67
68 5
        return $this;
69
    }
70
71
    /**
72
     * A short way to set some classic options to cURL a web page.
73
     *
74
     * @return self
75
     */
76 5
    public function setDefaultGetOptions(
77
        $connectTimeOut = 5,
78
        $timeOut = 10,
79
        $dnsCacheTimeOut = 600,
80
        $followLocation = true,
81
        $maxRedirs = 5
82
    ) {
83
        $this
84 5
            ->setOpt(CURLOPT_AUTOREFERER, 1)
85 5
            ->setOpt(CURLOPT_FOLLOWLOCATION, $followLocation)
86 5
            ->setOpt(CURLOPT_MAXREDIRS, $maxRedirs)
87 5
            ->setOpt(CURLOPT_CONNECTTIMEOUT, $connectTimeOut)
88 5
            ->setOpt(CURLOPT_DNS_CACHE_TIMEOUT, $dnsCacheTimeOut)
89 5
            ->setOpt(CURLOPT_TIMEOUT, $timeOut)
90
             //->setOpt(CURLOPT_SSL_VERIFYPEER,    0);
91
        ;
92
93 5
        return $this;
94
    }
95
96
    /**
97
     * A short way to set some classic options to cURL a web page quickly
98
     * (but loosing some data like header, cookie...).
99
     *
100
     * @return self
101
     */
102
    public function setDefaultSpeedOptions(bool $cookie = false)
103
    {
104
        $this->setOpt(CURLOPT_SSL_VERIFYHOST, 0);
105
        $this->setOpt(CURLOPT_SSL_VERIFYPEER, 0);
106
107
        if (!$this->returnHeader) {
108
            $this->setOpt(CURLOPT_HEADER, 0);
109
        }
110
        if (!$cookie) {
111
            $this->setOpt(CURLOPT_COOKIE, 0);
112
        }
113
        $this->setDefaultGetOptions(5, 10, 600, true, 1);
114
        $this->setEncodingGzip();
115
116
        return $this;
117
    }
118
119
    /**
120
     * Call it if you want header informations.
121
     * After self::execute(), you would have this informations with getHeader();.
122
     *
123
     * @return self
124
     */
125 5
    public function setReturnHeader($only = false)
126
    {
127 5
        $this->setOpt(CURLOPT_HEADER, 1);
128 5
        $this->returnHeader = $only ? 2 : 1;
129
130 5
        if ($only) {
131
            $this->setOpt(CURLOPT_RETURNTRANSFER, 0);
132
            $this->setOpt(CURLOPT_NOBODY, 1);
133
        }
134
135 5
        return $this;
136
    }
137
138
    /**
139
     * An self::setOpt()'s alias to add a cookie to your request.
140
     *
141
     * @param string $cookie
142
     *
143
     * @return self
144
     */
145
    public function setCookie($cookie)
146
    {
147
        $this->setOpt(CURLOPT_COOKIE, $cookie);
148
149
        return $this;
150
    }
151
152
    /**
153
     * An self::setOpt()'s alias to add a referrer to your request.
154
     *
155
     * @param string $referrer
156
     *
157
     * @return self
158
     */
159 2
    public function setReferrer($referrer)
160
    {
161 2
        $this->setOpt(CURLOPT_REFERER, $referrer);
162
163 2
        return $this;
164
    }
165
166
    /**
167
     * An self::setOpt()'s alias to add an user-agent to your request.
168
     *
169
     * @param string $ua
170
     *
171
     * @return self
172
     */
173 5
    public function setUserAgent($ua)
174
    {
175 5
        $this->setOpt(CURLOPT_USERAGENT, $ua);
176
177 5
        return $this;
178
    }
179
180
    /**
181
     * A short way to set post's options to cURL a web page.
182
     *
183
     * @param mixed if it's an array, will be converted via http build query
0 ignored issues
show
Bug introduced by
The type PiedWeb\Curl\if was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
184
     *
185
     * @return self
186
     */
187
    public function setPost($post)
188
    {
189
        $this->setOpt(CURLOPT_CUSTOMREQUEST, 'POST');
190
        $this->setOpt(CURLOPT_POST, 1);
191
        $this->setOpt(CURLOPT_POSTFIELDS, is_array($post) ? http_build_query($post) : $post);
192
193
        return $this;
194
    }
195
196
    /**
197
     * If you want to request the URL and hope get the result gzipped.
198
     * The output will be automatically uncompress with execute();.
199
     *
200
     * @return self
201
     */
202 5
    public function setEncodingGzip()
203
    {
204 5
        $this->setOpt(CURLOPT_ENCODING, 'gzip, deflate');
205 5
        $this->gzip = true;
206
207 5
        return $this;
208
    }
209
210
    /**
211
     * If you want to request the URL with a (http|socks...) proxy (public or private).
212
     *
213
     * @param string $proxy [scheme]IP:PORT[:LOGIN:PASSWORD]
214
     *                      Eg. : socks5://98.023.023.02:1098:cUrlRequestProxId:SecretPassword
215
     *
216
     * @return self
217
     */
218
    public function setProxy($proxy)
219
    {
220
        if (!empty($proxy)) {
221
            $scheme = Helper::getSchemeFrom($proxy);
222
            $proxy = explode(':', $proxy);
223
            $this->setOpt(CURLOPT_HTTPPROXYTUNNEL, 1);
224
            $this->setOpt(CURLOPT_PROXY, $scheme.$proxy[0].':'.$proxy[1]);
225
            if (isset($proxy[2])) {
226
                $this->setOpt(CURLOPT_PROXYUSERPWD, $proxy[2].':'.$proxy[3]);
227
            }
228
        }
229
230
        return $this;
231
    }
232
233
    /**
234
     * @param mixed $ContentType string or array
235
     *
236
     * @return self
237
     */
238 2
    public function setDownloadOnlyIf($ContentType = 'text/html')
239
    {
240 2
        $this->setReturnHeader();
241
242 2
        $this->filter = is_array($ContentType) ? $ContentType : [$ContentType];
243 2
        $this->setOpt(CURLOPT_HEADERFUNCTION, [$this, 'checkHeaderContentType']);
244 2
        $this->setOpt(CURLOPT_NOBODY, 1);
245
246 2
        return $this;
247
    }
248
249 2
    public function checkHeaderContentType($handle, $line)
250
    {
251 2
        if (is_string($line)) {
252 2
            foreach ($this->filter as $filter) {
253 2
                if (Helper::checkContentType($line, $filter)) {
254 2
                    $this->setOpt(CURLOPT_NOBODY, 0); //curl_setopt($handle, CURLOPT_NOBODY, 0);
255
                }
256
            }
257
        }
258
259 2
        return strlen($line);
260
    }
261
262
    /**
263
     * Execute the request.
264
     *
265
     * @return Requested
0 ignored issues
show
Bug introduced by
The type PiedWeb\Curl\Requested was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
266
     */
267 5
    public function exec()
268
    {
269 5
        $return = Response::get($this->handle, $this->url, $this->returnHeader, $this->gzip);
270
271 5
        if ($return instanceof Response) {
272 2
            $this->setReferrer($return->getEffectiveUrl());
273
        }
274
275 5
        return $return;
276
    }
277
278
    /**
279
     * Return the last error number (curl_errno).
280
     *
281
     * @return int the error number or 0 (zero) if no error occurred
282
     */
283
    public function hasError()
284
    {
285
        return curl_errno($this->handle);
286
    }
287
288
    /**
289
     * Return a string containing the last error for the current session (curl_error).
290
     *
291
     * @return string the error message or '' (the empty string) if no error occurred
292
     */
293
    public function getError()
294
    {
295
        return curl_error($this->handle);
296
    }
297
298
    /**
299
     * Get information regarding the request.
300
     *
301
     * @param int This may be one of the following constants:
0 ignored issues
show
Bug introduced by
The type PiedWeb\Curl\This was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
302
     *            http://php.net/manual/en/function.curl-getinfo.php
303
     *
304
     * @return array|string|false
305
     */
306
    public function getInfo(?int $opt)
307
    {
308
        return $opt ? curl_getinfo($this->handle, $opt) : curl_getinfo($this->handle);
309
    }
310
311
    /**
312
     * Close the connexion
313
     * Call curl_reset function.
314
     */
315
    public function close()
316
    {
317
        curl_reset($this->handle);
318
    }
319
}
320