GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Test Failed
Push — master ( 002ab3...f4053f )
by sunsky
03:32
created

Request::cert()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 4
crap 1
1
<?php
2
/**
3
 *
4
 * @author  [email protected] [email protected]
5
 * Date: 2017/6/16
6
 * Time: 10:02
7
 * @version $Id: $
8
 * @since 1.0
9
 * @copyright Sina Corp.
10
 */
11
12
namespace MultiHttp;
13
14
use MultiHttp\Exception\InvalidArgumentException;
15
16
class Request extends Http
0 ignored issues
show
Bug introduced by
Possible parse error: class missing opening or closing brace
Loading history...
17
{
18
<<<<<<< HEAD
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_SL, expecting T_FUNCTION or T_CONST
Loading history...
19
    const MAX_REDIRECTS_DEFAULT = 10;
20
=======
21
    /**
22
     * you can implement more traits
23
     */
24
    use JsonTrait;
25
26
>>>>>>> 1799bc479182f58431deae9f8975bf80f1e7cee6
27
    protected static $curlAlias = array(
28
        'url' => 'CURLOPT_URL',
29
        'uri' => 'CURLOPT_URL',
30
        'debug' => 'CURLOPT_VERBOSE',//for debug verbose
31
        'method' => 'CURLOPT_CUSTOMREQUEST',
32
        'data' => 'CURLOPT_POSTFIELDS', // array or string , file begin with '@'
33
        'ua' => 'CURLOPT_USERAGENT',
34
        'timeout' => 'CURLOPT_TIMEOUT', // (secs) 0 means indefinitely
35
        'connect_timeout' => 'CURLOPT_CONNECTTIMEOUT',
36
        'referer' => 'CURLOPT_REFERER',
37
        'binary' => 'CURLOPT_BINARYTRANSFER',
38
        'port' => 'CURLOPT_PORT',
39
        'header' => 'CURLOPT_HEADER', // TRUE:include header
40
        'headers' => 'CURLOPT_HTTPHEADER', // array
41
        'download' => 'CURLOPT_FILE', // writing file stream (using fopen()), default is STDOUT
42
        'upload' => 'CURLOPT_INFILE', // reading file stream
43
        'transfer' => 'CURLOPT_RETURNTRANSFER', // TRUE:return string; FALSE:output directly (curl_exec)
44
        'follow_location' => 'CURLOPT_FOLLOWLOCATION',
45
        'timeout_ms' => 'CURLOPT_TIMEOUT_MS', // milliseconds,  libcurl version > 7.36.0 ,
46
<<<<<<< HEAD
47
=======
48
        'expects_mime' => null, //expected mime
49
        'send_mime' => null, //send mime
50
        'ip' => null,//specify ip to send request
51
        'callback' => null,//callback on end
52
53
>>>>>>> 1799bc479182f58431deae9f8975bf80f1e7cee6
54
    );
55
    protected static $logger;
56
    public $curlHandle;
57
    public
58
        $uri,
59
<<<<<<< HEAD
60
        $timeout,
61
        $maxRedirects,
62
        $followRedirects;
63
    public $cert;
64
    public $key;
65
    public $passphrase;
66
    public $encoding;
67
    public $payload;
68
    public $retryTimes;
69
70
    /**
71
     * @var int seconds
72
     */
73
    public $retryDuration;
74
    protected $options = array(
75
        'CURLOPT_MAXREDIRS' => 10,
76
        'header' => true,
77
        'method' => self::GET,
78
        'transfer' => true,
79
        'follow_location' => true,
80
        'timeout' => 0,
81
//        'ip' => null, //host, in string, .e.g: 172.16.1.1:888
82
        'retry_times' => 1,//redo task when failed
83 2
        'retry_duration' => 0,//in seconds
84
    );
85 2
    protected $endCallback;
86
    protected $withURIQuery;
87
    protected $hasInitialized = false;
88
=======
89
        $sendMime,
90 2
        $expectedMime,
91
        $timeout,
92 2
        $maxRedirects,
93
        $encoding,
94
        $payload,
95
        $retryTimes,
96
        /**
97
         * @var int seconds
98 1
         */
99
        $retryDuration,
100 1
        $followRedirects;
101 1
102
    protected
103
        $body,
104
        $endCallback,
105
        $withURIQuery,
106
        $hasInitialized = false,
107 2
        /**
108
         * @var array
109 2
         */
110 2
        $options = array(
111 2
            'CURLOPT_MAXREDIRS' => 10,
112 2
            'CURLOPT_SSL_VERIFYPEER' => false,//for https
113 2
            'CURLOPT_SSL_VERIFYHOST' => 0,//for https
114 2
            'CURLOPT_IPRESOLVE' => CURL_IPRESOLVE_V4,//ipv4 first
115 2
//            'CURLOPT_SAFE_UPLOAD' => false,// compatible with PHP 5.6.0
116 2
            'header' => true,
117 2
            'method' => self::GET,
118 2
            'transfer' => true,
119
            'headers' => array(),
120
            'follow_location' => true,
121
            'timeout' => 0,
122
            //        'ip' => null, //host, in string, .e.g: 172.16.1.1:888
123
            'retry_times' => 1,//redo task when failed
124
            'retry_duration' => 0,//in seconds
125 2
        );
126
127 2
>>>>>>> 1799bc479182f58431deae9f8975bf80f1e7cee6
128 2
129
    protected function __construct()
130
    {
131
132
    }
133
134
    public static function create()
135 2
    {
136
        return new self;
137 2
    }
138 2
139 2
    public static function setLogger($logger)
140
    {
141
        self::$logger = $logger;
142
    }
143
    /**
144
     * Specify   timeout
145
     * @param float|int $timeout seconds to timeout the HTTP call
146
     * @return Request
147 2
     */
148
    public function timeout($timeout)
149 2
    {
150 2
        $this->timeout = $timeout;
151
        return $this;
152
    }
153
154
    /**
155
     * @return Request
156
     */
157
    public function noFollow()
158
    {
159
        return $this->follow(0);
160
    }
161
162
    /**
163
     * If the response is a 301 or 302 redirect, automatically
164
     * send off another request to that location
165
     * @param int $follow follow or not to follow or maximal number of redirects
166
     * @return Request
167
     */
168
    public function follow($follow)
169
    {
170
        $this->maxRedirects = abs($follow);
171
        $this->followRedirects = $follow > 0;
172
        return $this;
173
    }
174
175
    /**
176
     * Specify   timeout
177 1
     * @param float|int $timeout seconds to timeout the HTTP call
178
     * @return Request
179 1
     */
180 1
    public function timeout($timeout)
181 1
    {
182 1
        $this->timeout = $timeout;
183
        return $this;
184
    }
185
186
    public function noFollow()
187
    {
188
        return $this->follow(0);
189
    }
190
191
    /**
192
     * If the response is a 301 or 302 redirect, automatically
193
     * send off another request to that location
194
     * @param int $follow follow or not to follow or maximal number of redirects
195
     * @return Request
196 2
     */
197
    public function follow($follow)
198 2
    {
199
<<<<<<< HEAD
200
        $this->maxRedirects = abs($follow);
201
        $this->followRedirects = $follow > 0;
202
=======
203
        $this->sendMime = $mime;
204
//        $this->addHeader('Content-type', Mime::getFullMime($mime));
205 2
>>>>>>> 1799bc479182f58431deae9f8975bf80f1e7cee6
206
        return $this;
207 2
    }
208 2
209 2
    public function endCallback()
210
    {
211
        return $this->endCallback;
212
    }
213
214
    public function hasEndCallback()
215
    {
216 2
        return isset($this->endCallback);
217
    }
218 2
219 2
    public function uri($uri)
220 2
    {
221 2
        $this->uri = $uri;
222 2
        return $this;
223 2
    }
224 2
225
<<<<<<< HEAD
226
    public function hasCert()
227
    {
228
        return isset($this->cert) && isset($this->key);
229
    }
230
231 1
    /**
232
     * Use Client Side Cert Authentication
233 1
     * @param string $key file path to client key
234 1
     * @param string $cert file path to client cert
235 1
     * @param string $passphrase for client key
236 1
     * @param string $encoding default PEM
237 1
     * @return Request
238 1
     */
239
    public function cert($cert, $key, $passphrase = null, $encoding = 'PEM')
240
    {
241 1
        $this->cert = $cert;
242 1
        $this->key = $key;
243
        $this->passphrase = $passphrase;
244
        $this->encoding = $encoding;
245
        return $this;
246
    }
247
248
    public function body($payload, $mimeType = null)
249
    {
250
        $this->mime($mimeType);
251 1
        $this->payload = $payload;
252
        // Iserntentially don't call _serializePayload yet.  Wait until
253 1
        // we actually send off the request to convert payload to string.
254
        // At that time, the `serialized_payload` is set accordingly.
255
        return $this;
256
    }
257
    public function mime($mime)
258
    {
259
        if (empty($mime)) return $this;
260
        $this->content_type = $this->expected_type = Mime::getFullMime($mime);
261
        if ($this->isUpload()) {
262
            $this->neverSerializePayload();
263 2
        }
264
        return $this;
265 2
    }
266 2
    public function addHeader($header_name, $value)
267
    {
268 2
        $this->headers[$header_name] = $value;
269
        return $this;
270
    }
271
=======
272
273
>>>>>>> 1799bc479182f58431deae9f8975bf80f1e7cee6
274
275 2
    public function addHeaders(array $headers)
276
    {
277 2
        foreach ($headers as $header => $value) {
278 2
            $this->addHeader($header, $value);
279 2
        }
280
        return $this;
281
    }
282
    public function expectsType($mime)
283
<<<<<<< HEAD
284
=======
285
    {
286
        return $this->expects($mime);
287
    }
288 1
    public function sendType($mime)
289
    {
290 1
        return $this->contentType = $mime;
291
    }
292
    public function expects($mime)
293
    {
294
        if (empty($mime)) return $this;
295
        $this->expected_type = Mime::getFullMime($mime);
296
        return $this;
297
    }
298
299 1
    /**
300
     * @return mixed
301 1
     */
302
    public function endCallback()
303
>>>>>>> 1799bc479182f58431deae9f8975bf80f1e7cee6
304
    {
305
        return $this->expects($mime);
306
    }
307
    public function sendType($mime)
308
    {
309 1
        return $this->contentType = $mime;
310
    }
311 1
    public function expects($mime)
312
    {
313
        if (empty($mime)) return $this;
314
        $this->expected_type = Mime::getFullMime($mime);
315
        return $this;
316
    }
317
    /**
318
     * @param $field alias or field name
319 1
     * @return bool|mixed
320
     */
321 1
    public function getIni($field)
322
    {
323
        $alias = self::optionAlias($field);
324
        return isset($this->options[$alias]) ? $this->options[$alias] : false;
325
    }
326
327
    /**
328
     * @param $key
329 1
     * @return mixed
330
     */
331 1
    protected static function optionAlias($key)
332
    {
333
        $alias = false;
334
        if (isset(self::$curlAlias[$key])) {
335
            $alias = self::$curlAlias[$key];
336
        } elseif ((substr($key, 0, strlen('CURLOPT_')) == 'CURLOPT_') && defined($key)) {
337
            $alias = $key;
338
        }
339 1
        return $alias;
340
    }
341 1
342
<<<<<<< HEAD
343
    public function addQuery($data)
344
=======
345
    /**
346
     * @param $queryData
347
     * @return $this
348
     */
349 2
    public function addQuery($queryData)
350
>>>>>>> 1799bc479182f58431deae9f8975bf80f1e7cee6
351 2
    {
352
        if (!empty($queryData)) {
353
            if (is_array($queryData)) {
354
                $this->withURIQuery = http_build_query($queryData);
355
            } else if (is_string($queryData)) {
356
                $this->withURIQuery = $queryData;
357
            } else {
358 2
                throw new InvalidArgumentException('data must be array or string');
359
            }
360
        }
361 2
        return $this;
362 2
    }
363 2
<<<<<<< HEAD
364 2
365 2
=======
366
    /**
367
     * @param $uri
368
     * @param null $payload
369
     * @param array $options
370
     * @return Request
371 2
     */
372 1
>>>>>>> 1799bc479182f58431deae9f8975bf80f1e7cee6
373 1
    public function post($uri, $payload = null, array $options = array())
374 2
    {
375 2
        return $this->ini(Http::POST, $uri, $payload, $options);
376 2
    }
377
378 2
    /**
379
     * @param $uri
380
     * @param null $payload
381
<<<<<<< HEAD
382
=======
383
     * @param array $options
384 2
     * @param null $response
385
     * @return string
386 2
     */
387 2
    public function quickPost($uri, $payload = null, array $options = array(), &$response = null)
388 2
    {
389 2
        $response = $this->post($uri, $payload, $options)->send();
390 2
        return $response->body;
391
    }
392
393
394
    /**
395
     * @param $method
396 2
     * @param $url
397
     * @param $data
398 2
>>>>>>> 1799bc479182f58431deae9f8975bf80f1e7cee6
399 2
     * @param array $options
400
     * @param null $response
401
     * @return string
402
     */
403 2
    public function quickPost($uri, $payload = null, array $options = array(), &$response = null)
404 1
    {
405
        $response = $this->post($uri, $payload, $options)->send();
406 1
        return $response->body;
407
    }
408 2
    /*  no body  */
409 1
410
    protected function ini($method, $url,  $data , array $options = array())
411 1
    {
412
        $options = array('url' => $url, 'method' => $method, 'data' => $data) + $options;
413 2
        $this->addOptions($options);
414
415
        return $this;
416 2
    }
417 2
418 2
    public function addOptions(array $options = array())
419 2
    {
420 1
        $this->options = $options + $this->options;
421 1
        $this->uri = $this->options['url'];
422 1
        return $this;
423 2
    }
424
425 2
    function put($uri, $payload = null, array $options = array())
426 2
    {
427
        return $this->ini(Http::PUT, $uri, $payload, $options);
428 2
    }
429
430 2
    function patch($uri, $payload = null, array $options = array())
431 2
    {
432 2
        return $this->ini(Http::PATCH, $uri, $payload, $options);
433 2
    }
434 2
435 2
    public function get($uri, array $options = array())
436 2
    {
437
        return $this->ini(Http::GET, $uri, array(), $options);
438
    }
439 2
440
441 2
    /**
442 2
     * @param $uri
443
     * @param array $options
444 2
     * @param null $response
445
     * @return string
446
     */
447
    public function quickGet($uri, array $options = array(), &$response = null)
448
    {
449
        $response = $this->get($uri, $options)->send();
450
        return $response->body;
451
    }
452
453
    /**
454
     * @param $uri
455
     * @param array $options
456 2
     * @param null $response
457 2
     * @return string
458 2
     */
459 2
    public function quickGet($uri, array $options = array(), &$response = null)
460 1
    {
461
        $response = $this->get($uri, $options)->send();
462 2
        return $response->body;
463
    }
464
465 2
    function options($uri, array $options = array())
466 2
    {
467
        return $this->ini(Http::OPTIONS, $uri, array(), $options);
468 2
    }
469
470
    function head($uri, array $options = array())
471 2
    {
472
        return $this->ini(Http::HEAD, $uri, array('CURLOPT_NOBODY' => true), $options);
473 2
    }
474 2
475 2
    function delete($uri, array $options = array())
476 2
    {
477 2
        return $this->ini(Http::DELETE, $uri, array(), $options);
478 2
    }
479 2
480
    function trace($uri, array $options = array())
481 2
    {
482 2
        return $this->ini(Http::TRACE, $uri, array(), $options);
483
    }
484
485
    /**
486
     * @return Response
487
     */
488 2
    public function send()
489
    {
490 2
        if (!$this->hasInitialized)
491
            $this->applyOptions();
492
        $response = $this->makeResponse();
493
        if ($this->endCallback) {
494 2
            $func = $this->endCallback;
495 2
            $func($response);
496
        }
497
        return $response;
498
    }
499
500
    public function applyOptions()
501
    {
502 2
        $curl = curl_init();
503
        $this->curlHandle = $curl;
504 2
        $this->prepare();
505 2
        $this->hasInitialized = true;
506 2
        return $this;
507
    }
508 2
509 2
    protected function prepare()
510 2
    {
511 2
        if (empty($this->options['url'])) {
512 2
            throw new InvalidArgumentException('url can not empty');
513 2
        }
514 2
515 2
        if (isset($this->options['retry_times'])) {
516
<<<<<<< HEAD
517
           $this->retryTimes = abs($this->options['retry_times']);
518
        }
519
520
        if (isset($this->options['retry_duration'])) {
521
           $this->retryDuration = abs($this->options['retry_duration']);
522
=======
523 2
            $this->retryTimes = abs($this->options['retry_times']);
524
        }
525 2
526 2
        if (isset($this->options['retry_duration'])) {
527 2
            $this->retryDuration = abs($this->options['retry_duration']);
528 2
        }
529 2
530 2
        if(isset($this->options['expects_mime'])){
531
            $this->expectsMime($this->options['expects_mime']);
532
        }
533
534
        if(isset($this->options['send_mime'])){
535
            $this->sendMime($this->options['send_mime']);
536
        }
537
538
//        if(!empty($this->options['data']) && !Http::hasBody($this->options['method'])){
539
//            $this->withURIQuery =  is_array($this->options['data']) ? http_build_query($this->options['data']) : $this->options['data'];
540
//        }
541
        if (isset($this->withURIQuery)) {
542
            $this->options['url'] .= strpos($this->options['url'], '?') === FALSE ? '?' : '&';
543
            $this->options['url'] .= $this->withURIQuery;
544
>>>>>>> 1799bc479182f58431deae9f8975bf80f1e7cee6
545
        }
546
547
        if (isset($this->options['data'])) {
548
            $this->options['data'] = is_array($this->options['data']) ? http_build_query($this->options['data']) : $this->options['data'];//for better compatibility
549
        }
550
        if (isset($this->withURIQuery)) {
551
            $this->options['url'] .= strpos($this->options['url'], '?') === FALSE ? '?' : '&';
552
            $this->options['url'] .= $this->withURIQuery;
553
        }
554
        if (isset($this->options['callback'])) {
555
            $this->onEnd($this->options['callback']);
556
<<<<<<< HEAD
557
            unset($this->options['callback']);
558
=======
559
>>>>>>> 1799bc479182f58431deae9f8975bf80f1e7cee6
560
        }
561
        //swap ip and host
562
        if (!empty($this->options['ip'])) {
563
            $matches = array();
564
            preg_match('/\/\/([^\/]+)/', $this->options['url'], $matches);
565
            $host = $matches[1];
566
            if (empty($this->options['headers']) || !is_array($this->options['headers'])) {
567
                $this->options['headers'] = array('Host: ' . $host);
568
            } else {
569
                $this->options['headers'][] = 'Host: ' . $host;
570
            }
571
            $this->options['url'] = preg_replace('/\/\/([^\/]+)/', '//' . $this->options['ip'], $this->options['url']);
572
<<<<<<< HEAD
573
            unset($this->options['ip']);
574
=======
575
>>>>>>> 1799bc479182f58431deae9f8975bf80f1e7cee6
576
            unset($host);
577
        }
578
        //process version
579
        if (!empty($this->options['http_version'])) {
580
            $version = $this->options['http_version'];
581
            if ($version == '1.0') {
582
                $this->options['CURLOPT_HTTP_VERSION'] = CURLOPT_HTTP_VERSION_1_0;
583
            } elseif ($version == '1.1') {
584
                $this->options['CURLOPT_HTTP_VERSION'] = CURLOPT_HTTP_VERSION_1_1;
585
            }
586
587
            unset($version);
588
        }
589
590
        //convert secs to milliseconds
591
        if (defined('CURLOPT_TIMEOUT_MS')) {
592
            if (!isset($this->options['timeout_ms'])) {
593
                $this->options['timeout_ms'] = intval($this->options['timeout'] * 1000);
594
            } else {
595
                $this->options['timeout_ms'] = intval($this->options['timeout_ms']);
596
            }
597
        }
598
599
        $cURLOptions = self::filterAndRaw($this->options);
600
<<<<<<< HEAD
601
602
=======
603
        if(isset($this->body))$cURLOptions[CURLOPT_POSTFIELDS] = $this->body;//use serialized body not raw data
604
>>>>>>> 1799bc479182f58431deae9f8975bf80f1e7cee6
605
        curl_setopt_array($this->curlHandle, $cURLOptions);
606
607
        return $this;
608
    }
609
610
<<<<<<< HEAD
611
=======
612
    public function serializeBody()
613
    {
614
        if (isset($this->options['data'])) {
615
            if (isset($this->sendMime)) {
616
                $method = $this->sendMime;
617
                if (!method_exists($this, $method)) throw new InvalidOperationException($method . ' is not exists in ' . __CLASS__);
618
                $this->body = $this->$method($this->options['data']);
619
            } else {
620
                $this->body =  $this->options['data'];
621
            }
622
623
        }
624
    }
625
626
    /**
627
     * @param callable $callback
628
     * @return $this
629
     */
630
>>>>>>> 1799bc479182f58431deae9f8975bf80f1e7cee6
631
    public function onEnd(callable $callback)
632
    {
633
        if (!is_callable($callback)) {
634
            throw new InvalidArgumentException('callback not is callable :' . print_r($callback, 1));
635
        }
636
637
        $this->endCallback = $callback;
638
        return $this;
639
    }
640
641
    protected static function filterAndRaw(array &$options)
642
    {
643
        $opts = array();
644
        foreach ($options as $key => $val) {
645
            $alias = self::optionAlias($key);
646
            $options[$alias] = $val;
647
            if ($alias) {
648
                $opts[constant($alias)] = $val;
649
            }
650
            unset($options[$key]);
651
        }
652
        return $opts;
653
    }
654
655
656
    public function makeResponse($isMultiCurl = false)
657
    {
658
        $handle = $this->curlHandle;
659
        $body = $errno = null;
660
        Helper::retry($this->retryTimes, function()use(&$body, &$errno, $isMultiCurl, $handle){
661
            $body = $isMultiCurl ? curl_multi_getcontent($handle) : curl_exec($handle);
662
            $errno = curl_errno($handle);
663
<<<<<<< HEAD
664
            var_dump(curl_error($handle), time());
665
            ob_flush();
666
            flush();
667
=======
668
>>>>>>> 1799bc479182f58431deae9f8975bf80f1e7cee6
669
            return 0 == $errno;
670
        }, $this->retryDuration);
671
672
        $info = curl_getinfo($this->curlHandle);
673
        $error = curl_error($this->curlHandle);
674
        $response = Response::create($this, $body, $info, $errno, $error);
675
        if (!is_null(self::$logger)) {
676
            self::log($response);
677
        }
678
679
        return $response;
680
    }
681
682
    private static function log(Response $response)
683
    {
684
        if ($response->hasErrors()) {
685
            self::$logger->error($response->request->getURI() . "\t" . $response->error, array(
686
                'response' => print_r($response, 1),
687
            ));
688
        }
689
690
    }
691
}
692