RequestHelper::setDecodeContentFalse()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
c 0
b 0
f 0
ccs 0
cts 3
cp 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
crap 2
1
<?php
2
/**
3
 * Copyright (c) Padosoft.com 2016.
4
 */
5
6
namespace Padosoft\HTTPClient;
7
8
use Psr\Http\Message\StreamInterface;
9
10
11
/**
12
 * Class RequestHelper
13
 * Simple Class to easy contruct you request.
14
 * @package Padosoft\HTTPClient
15
 */
16
class RequestHelper
17
{
18
    /**
19
     * @var array
20
     */
21
    protected $options  = array();
22
23
    /**
24
     * RequestHelper constructor.
25
     */
26 15
    public function __construct()
27
    {
28
        //set defaults
29 15
        $this->setDefaults();
30 15
    }
31
32
    /**
33
     * allow_redirects: (bool|array) Controls redirect behavior. Pass false
34
     * to disable redirects, pass true to enable redirects, pass an
35
     * associative to provide custom redirect settings. Defaults to "false".
36
     * This option only works if your handler has the RedirectMiddleware. When
37
     * passing an associative array, you can provide the following key value
38
     * pairs:
39
     *
40
     * - max: (int, default=5) maximum number of allowed redirects.
41
     * - strict: (bool, default=false) Set to true to use strict redirects
42
     *   meaning redirect POST requests with POST requests vs. doing what most
43
     *   browsers do which is redirect POST requests with GET requests
44
     * - referer: (bool, default=true) Set to false to disable the Referer
45
     *   header.
46
     * - protocols: (array, default=['http', 'https']) Allowed redirect
47
     *   protocols.
48
     * - on_redirect: (callable) PHP callable that is invoked when a redirect
49
     *   is encountered. The callable is invoked with the request, the redirect
50
     *   response that was received, and the effective URI. Any return value
51
     *   from the on_redirect function is ignored.
52
     * @param int $max
53
     * @param bool $strict
54
     * @param bool $referer
55
     * @param array $protocolsArray
56
     * @param callable|null $onRedirect
57
     * @return $this
58
     */
59
    public function setAllowRedirects($max=5,$strict=false,$referer=true,$protocolsArray=['http', 'https'],callable $onRedirect=null)
60
    {
61
        if(!isset($max) || !preg_match("/^(0)$|^([1-9][0-9]*)$/",$max)) {
62
            $max=5;
63
        }
64
        if(!isset($strict) || !is_bool($strict)) {
65
            $strict=false;
66
        }
67
        if(!isset($referer) || !is_bool($referer)) {
68
            $referer=true;
69
        }
70
71
        if(!isset($protocolsArray) || !is_array($protocolsArray)) {
72
            $protocolsArray=['http', 'https'];
73
        }
74
75
        if(!is_callable($onRedirect)){
76
            $onRedirect = null;
77
        }
78
79
        $this->options['allow_redirects'] = ['max' => $max
80
                                                , 'strict' => $strict
81
                                                , 'referer' => $referer
82
                                                , 'protocolsArray' => $protocolsArray
83
                                                , 'onRedirect' => $onRedirect
84
                                            ];
85
        return $this;
86
    }
87
88
    /**
89
     * auth: Pass HTTP authentication parameters to use
90
     * with the request.
91
     *
92
     * @param string $username
93
     * @param string $password
94
     * @param string $typeAuthentication
95
     * @return $this
96
     */
97 6
    public function setAuth($username, $password, $typeAuthentication=TypeAuthentication::BASIC)
98
    {
99 6
        if(!TypeAuthentication::isValidValue($typeAuthentication)) {
100
            $typeAuthentication=TypeAuthentication::BASIC;
101
        }
102 6
        $this->options['auth'] = [$username, $password, $typeAuthentication];
103 6
        return $this;
104
    }
105
    /**
106
     * body: (string|null|callable|iterator|object) Body to send in the
107
     * request.
108
     * @param (string|null|callable|iterator|object) $body
109
     * @return $this
110
     */
111
    public function setBody($body)
112
    {
113
        if(null!==$body && !is_object($body) && !is_string($body) && !is_callable($body) && !is_a($body, \Iterator::class))
114
        {
115
            return $this;
116
        }
117
118
        $this->options['body'] = $body;
119
        return $this;
120
    }
121
    /**
122
     * cert: (string|array) Set to a string to specify the path to a file
123
     * containing a PEM formatted SSL client side certificate. If a password
124
     * is required, then set cert to an array containing the path to the PEM
125
     * file in the first array element followed by the certificate password
126
     * in the second array element.
127
     *
128
     * @param (string|array) $certificate
129
     * @return $this
130
     */
131
    public function setCert($certificate)
132
    {
133
        if(!is_array($certificate) && !is_string($certificate))
134
        {
135
            return $this;
136
        }
137
138
        $this->options['cert'] = $certificate;
139
        return $this;
140
    }
141
    /**
142
     * cookies: (bool|GuzzleHttp\Cookie\CookieJarInterface)
143
     * Specifies whether or not cookies are used in a request or what cookie
144
     * jar to use or what cookies to send. This option only works if your
145
     * handler has the `cookie` middleware. Valid values are `false` and
146
     * an instance of {@see GuzzleHttp\Cookie\CookieJarInterface}.
147
     *
148
     * @param (bool|GuzzleHttp\Cookie\CookieJarInterface) $cookies
149
     * @return $this
150
     */
151
    public function setCookies($cookies)
152
    {
153
        if(!is_bool($$cookies) && !is_a($cookies, \GuzzleHttp\Cookie\CookieJarInterface::class))
154
        {
155
            $cookies = false;
156
        }
157
158
        $this->options['cookies'] = $cookies;
159
        return $this;
160
    }
161
    /**
162
     * connect_timeout: (float, default=0) Float describing the number of
163
     * seconds to wait while trying to connect to a server. Use 0 to wait
164
     * indefinitely (the default behavior).
165
     * @param int $secondConnectTimeout
166
     * @return $this
167
     */
168
    public function setConnectTimeout($secondConnectTimeout=0)
169
    {
170
        $this->options['connect_timeout'] = (float) $secondConnectTimeout;
171
        return $this;
172
    }
173
    /**
174
     * debug: (bool|resource) Set to true or set to a PHP stream returned by
175
     * fopen()  enable debug output with the HTTP handler used to send a
176
     * request.
177
     * @param $debug
178
     * @return $this
179
     */
180
    public function setDebug($debug)
181
    {
182
        if(!is_resource($debug) && !is_bool($debug))
183
        {
184
            return $this;
185
        }
186
187
        $this->options['debug'] = $debug;
188
        return $this;
189
    }
190
    /**
191
     * decode_content: (bool, default=true) Specify whether or not
192
     * Content-Encoding responses (gzip, deflate, etc.) are automatically
193
     * decoded.
194
     * @return $this
195
     */
196
    public function setDecodeContentTrue()
197
    {
198
        $this->options['decode_content']= true;
199
        return $this;
200
    }
201
    /**
202
     * decode_content: (bool, default=true) Specify whether or not
203
     * Content-Encoding responses (gzip, deflate, etc.) are automatically
204
     * decoded.
205
     * @return $this
206
     */
207
    public function setDecodeContentFalse()
208
    {
209
        $this->options['decode_content']= false;
210
        return $this;
211
    }
212
    /**
213
     * delay: (int) The amount of time to delay before sending in milliseconds.
214
     * @param int $millisecondDelay
215
     * @return $this
216
     */
217
    public function setDelay($millisecondDelay)
218
    {
219
        $this->options['delay'] = (int) $millisecondDelay;
220
        return $this;
221
    }
222
    /**
223
     * expect: (bool|integer) Controls the behavior of the
224
     * "Expect: 100-Continue" header.
225
     *
226
     * Set to `true` to enable the "Expect: 100-Continue" header for all
227
     * requests that sends a body. Set to `false` to disable the
228
     * "Expect: 100-Continue" header for all requests. Set to a number so that
229
     * the size of the payload must be greater than the number in order to send
230
     * the Expect header. Setting to a number will send the Expect header for
231
     * all requests in which the size of the payload cannot be determined or
232
     * where the body is not rewindable.
233
     *
234
     * By default, Guzzle will add the "Expect: 100-Continue" header when the
235
     * size of the body of a request is greater than 1 MB and a request is
236
     * using HTTP/1.1.
237
     *
238
     * @param (bool|integer) $expect
239
     * @return $this
240
     */
241
    public function setExpect($expect)
242
    {
243
        if(!is_bool($expect) && !is_int($expect)){
244
            return $this;
245
        }
246
247
        $this->options['expect']=$expect;
248
        return $this;
249
    }
250
    /**
251
     * form_params: (array) Associative array of form field names to values
252
     * where each value is a string or array of strings. Sets the Content-Type
253
     * header to application/x-www-form-urlencoded when no Content-Type header
254
     * is already present.
255
     *
256
     * @param array $form_params
257
     * @return $this
258
     */
259
    public function setFormParams($form_params)
260
    {
261
        if(!is_array($form_params)){
262
            return $this;
263
        }
264
265
        $this->options['form_params']=$form_params;
266
        return $this;
267
    }
268
    /**
269
     * headers: (array) Associative array of HTTP headers. Each value MUST be
270
     * a string or array of strings.
271
     *
272
     * @param array $headers
273
     * @return $this
274
     */
275
    public function setHeaders($headers)
276
    {
277
        if(!is_array($headers)){
278
            return $this;
279
        }
280
281
        $this->options['headers'] = $headers;
282
        return $this;
283
    }
284
    /**
285
     * http_errors: (bool, default=true) Set to false to disable exceptions
286
     * when a non- successful HTTP response is received. By default,
287
     * exceptions will be thrown for 4xx and 5xx responses. This option only
288
     * works if your handler has the `httpErrors` middleware.
289
     *
290
     * @return $this
291
     */
292 6
    public function setHttpErrorsTrue()
293
    {
294 6
        $this->options['http_errors'] =true;
295 6
        return $this;
296
    }
297
    /**
298
     * http_errors: (bool, default=true) Set to false to disable exceptions
299
     * when a non- successful HTTP response is received. By default,
300
     * exceptions will be thrown for 4xx and 5xx responses. This option only
301
     * works if your handler has the `httpErrors` middleware.
302
     *
303
     * @return $this
304
     */
305 15
    public function setHttpErrorsFalse()
306
    {
307 15
        $this->options['http_errors'] =false;
308 15
        return $this;
309
    }
310
    /**
311
     * json: (mixed) Adds JSON data to a request.
312
     * The provided value it will be JSON encoded
313
     * and a Content-Type header of application/json will be added to
314
     * the request if no Content-Type header is already present.
315
     *
316
     * @param $json
317
     * @return $this
318
     */
319 6
    public function setJson($json)
320
    {
321 6
        $this->options['json'] = $json;
322 6
        return $this;
323
    }
324
    /**
325
     * @param Multipart $multipart
326
     * @return $this
327
     */
328
    public function setMultipart(Multipart $multipart)
329
    {
330
        if($multipart===null){
331
            return $this;
332
        }
333
334
        $this->options['multipart']= $multipart->getMultipartArray();
335
        return $this;
336
    }
337
    /**
338
     * on_headers: (callable) A callable that is invoked when the HTTP headers
339
     * of the response have been received but the body has not yet begun to
340
     * download.
341
     *
342
     * @param callable $on_headers
343
     * @return $this
344
     */
345
    public function setOnHeaders(callable $on_headers)
346
    {
347
        if(!is_callable($on_headers)){
348
            return $this;
349
        }
350
351
        $this->options['on_headers']=$on_headers;
352
        return $this;
353
    }
354
    /**
355
     * on_stats: (callable) allows you to get access to transfer statistics of
356
     * a request and access the lower level transfer details of the handler
357
     * associated with your client. ``on_stats`` is a callable that is invoked
358
     * when a handler has finished sending a request. The callback is invoked
359
     * with transfer statistics about the request, the response received, or
360
     * the error encountered. Included in the data is the total amount of time
361
     * taken to send the request.
362
     *
363
     * @param callable $on_stats
364
     * @return $this
365
     */
366
    public function setOnStats(callable $on_stats)
367
    {
368
        if(!is_callable($on_stats)){
369
            return $this;
370
        }
371
372
        $this->options['on_stats'] = $on_stats;
373
        return $this;
374
    }
375
    /**
376
     * progress: (callable) Defines a function to invoke when transfer
377
     * progress is made. The function accepts the following positional
378
     * arguments: the total number of bytes expected to be downloaded, the
379
     * number of bytes downloaded so far, the number of bytes expected to be
380
     * uploaded, the number of bytes uploaded so far.
381
     *
382
     * @param callable $progress
383
     * @return $this
384
     */
385
    public function setProgress(callable $progress)
386
    {
387
        if(!is_callable($progress)){
388
            return $this;
389
        }
390
391
        $this->options['progress']= $progress;
392
        return $this;
393
    }
394
    /**
395
     * proxy: (string|array) Pass a string to specify an HTTP proxy, or an
396
     * array to specify different proxies for different protocols (where the
397
     * key is the protocol and the value is a proxy string).
398
     *
399
     * @param (string|array) $proxy
400
     * @return $this
401
     */
402
    public function setProxy($proxy)
403
    {
404
        if(!is_array($proxy) && !is_string($proxy)){
405
            return $this;
406
        }
407
408
        $this->options['proxy']= $proxy;
409
        return $this;
410
    }
411
    /**
412
     * query: (array|string) Associative array of query string values to add
413
     * to the request. This option uses PHP's http_build_query() to create
414
     * the string representation. Pass a string value if you need more
415
     * control than what this method provides
416
     *
417
     * @param (array|string) $query
418
     * @return $this
419
     */
420
    public function setQuery($query)
421
    {
422
        if(!is_array($query) && !is_string($query)) {
423
            return $this;
424
        }
425
426
        $this->options['query']=$query;
427
        return $this;
428
    }
429
    /**
430
     * sink: (resource|string|StreamInterface) Where the data of the
431
     * response is written to. Defaults to a PHP temp stream. Providing a
432
     * string will write data to a file by the given name.
433
     *
434
     * @param (resource|string|StreamInterface) $sink
435
     * @return $this
436
     */
437
    public function setSink($sink)
438
    {
439
        if(!is_resource($sink) && !is_string($sink) && !is_a($sink, StreamInterface::class))
440
        {
441
            return $this;
442
        }
443
444
        $this->options['sink']=$sink;
445
        return $this;
446
    }
447
    /**
448
     * synchronous: (bool) Set to true to inform HTTP handlers that you intend
449
     * on waiting on the response. This can be useful for optimizations. Note
450
     * that a promise is still returned if you are using one of the async
451
     * client methods.
452
     *
453
     * @return $this
454
     */
455
    public function setSynchronousTrue()
456
    {
457
        $this->options['synchronous'] = true;
458
        return $this;
459
    }
460
    /**
461
     * synchronous: (bool) Set to true to inform HTTP handlers that you intend
462
     * on waiting on the response. This can be useful for optimizations. Note
463
     * that a promise is still returned if you are using one of the async
464
     * client methods.
465
     *
466
     * @return $this
467
     */
468
    public function setSynchronousFalse()
469
    {
470
        $this->options['synchronous'] = false;
471
        return $this;
472
    }
473
    /**
474
     * ssl_key: (array|string) Specify the path to a file containing a private
475
     * SSL key in PEM format. If a password is required, then set to an array
476
     * containing the path to the SSL key in the first array element followed
477
     * by the password required for the certificate in the second element.
478
     *
479
     * @param (array|string) $ssl_key
480
     * @return $this
481
     */
482
    public function setSslKey($ssl_key)
483
    {
484
        if(!is_array($ssl_key) && !is_string($ssl_key))
485
        {
486
            return $this;
487
        }
488
489
        $this->options['ssl_key']=$ssl_key;
490
        return $this;
491
    }
492
    /**
493
     * stream: Set to true to attempt to stream a response rather than
494
     * download it all up-front.
495
     *
496
     * @param $stream
497
     * @return $this
498
     */
499
    public function setStream($stream)
500
    {
501
        $this->options['stream']=$stream;
502
        return $this;
503
    }
504
    /**
505
     * verify: (bool|string, default=true) Describes the SSL certificate
506
     * verification behavior of a request. Set to true to enable SSL
507
     * certificate verification using the system CA bundle when available
508
     * (the default). Set to false to disable certificate verification (this
509
     * is insecure!). Set to a string to provide the path to a CA bundle on
510
     * disk to enable verification using a custom certificate.
511
     *
512
     * @param (bool|string) $verify
513
     * @return $this
514
     */
515 3
    public function setVerify($verify)
516
    {
517 3
        if(!is_bool($verify) && !is_string($verify))
518 3
        {
519
            $verify = false;
520
        }
521
522 3
        $this->options['verify']=$verify;
523 3
        return $this;
524
    }
525
    /**
526
     * timeout: (float, default=0) Float describing the timeout of the
527
     * request in seconds. Use 0 to wait indefinitely (the default behavior).
528
     *
529
     * @param float $secondRequestTimeout
530
     * @return $this
531
     */
532
    public function setTimeout($secondRequestTimeout=0.0)
533
    {
534
        if(!is_float($secondRequestTimeout)){
535
            $secondRequestTimeout = (float) 0.0;
536
        }
537
538
        $this->options['timeout']=(float) $secondRequestTimeout;
539
        return $this;
540
    }
541
    /**
542
     * version: (float, default=1.1) Specifies the HTTP protocol version to attempt to use.
543
     *
544
     * @param float $version
545
     * @return $this
546
     */
547
    public function setVersion($version)
548
    {
549
        if(!is_float($version)){
550
            $version = (float) 1.1;
551
        }
552
553
        $this->options['version']=$version;
554
        return $this;
555
    }
556
557
    /**
558
     * @param $property
559
     * @return mixed
560
     */
561 15
    public function __get($property)
562
    {
563 15
        if (!property_exists($this, $property)) {
564
            return null;
565
        }
566
567 15
        return $this->$property;
568
    }
569
570
    /**
571
     * @param $property
572
     * @param $value
573
     * @return $this
574
     */
575
    public function __set($property, $value)
576
    {
577
        if (!property_exists($this, $property)) {
578
            return;
579
        }
580
581
        $this->$property = $value;
582
    }
583
584
    /**
585
     * Set the default Request headers.
586
     */
587 15
    public function setDefaults()
588
    {
589 15
        $this->setHttpErrorsFalse();
590 15
    }
591
}
592