Completed
Push — EventLoopContainer ( c9a84d...6e77fa )
by Vasily
04:04
created

Connection::onRead()   F

Complexity

Conditions 40
Paths 1365

Size

Total Lines 146
Code Lines 109

Duplication

Lines 11
Ratio 7.53 %

Importance

Changes 5
Bugs 2 Features 0
Metric Value
cc 40
eloc 109
c 5
b 2
f 0
nc 1365
nop 0
dl 11
loc 146
rs 2

How to fix   Long Method    Complexity   

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
namespace PHPDaemon\Clients\HTTP;
3
4
use PHPDaemon\Clients\HTTP\UploadFile;
5
use PHPDaemon\Core\Daemon;
6
use PHPDaemon\HTTPRequest\Generic;
7
use PHPDaemon\Network\ClientConnection;
8
9
/**
10
 * @package    NetworkClients
11
 * @subpackage HTTPClient
12
 * @author     Vasily Zorin <[email protected]>
13
 */
14
class Connection extends ClientConnection
15
{
16
    /**
17
     * State: headers
18
     */
19
    const STATE_HEADERS = 1;
20
21
    /**
22
     * State: body
23
     */
24
    const STATE_BODY = 2;
25
26
    /**
27
     * @var array Associative array of headers
28
     */
29
    public $headers = [];
30
31
    /**
32
     * @var integer Content length
33
     */
34
    public $contentLength = -1;
35
36
    /**
37
     * @var string Contains response body
38
     */
39
    public $body = '';
40
41
    /**
42
     * @var string End of line
43
     */
44
    protected $EOL = "\r\n";
45
46
    /**
47
     * @var array Associative array of Cookies
48
     */
49
    public $cookie = [];
50
51
    /**
52
     * @var integer Size of current chunk
53
     */
54
    protected $curChunkSize;
55
56
    /**
57
     * @var string
58
     */
59
    protected $curChunk;
60
61
    /**
62
     * @var boolean
63
     */
64
    public $chunked = false;
65
66
    /**
67
     * @var callback
68
     */
69
    public $chunkcb;
70
71
    /**
72
     * @var integer
73
     */
74
    public $protocolError;
75
76
    /**
77
     * @var integer
78
     */
79
    public $responseCode = 0;
80
81
    /**
82
     * @var string Last requested URL
83
     */
84
    public $lastURL;
85
86
    /**
87
     * @var array Raw headers array
88
     */
89
    public $rawHeaders = null;
90
91
    public $contentType;
92
93
    public $charset;
94
95
    public $eofTerminated = false;
96
97
    /**
98
     * @var \SplStack
99
     */
100
    protected $requests;
101
102
    /**
103
     * @var string
104
     */
105
    public $reqType;
106
107
    /**
108
     * Constructor
109
     */
110
    protected function init()
111
    {
112
        $this->requests = new \SplStack;
113
    }
114
115
    /**
116
     * Send request headers
117
     * @param $type
118
     * @param $url
119
     * @param &$params
120
     * @return void
121
     */
122
    protected function sendRequestHeaders($type, $url, &$params)
123
    {
124
        if (!is_array($params)) {
125
            $params = ['resultcb' => $params];
126
        }
127
        if (!isset($params['uri']) || !isset($params['host'])) {
128
            $prepared = Pool::parseUrl($url);
129
            if (!$prepared) {
130
                if (isset($params['resultcb'])) {
131
                    $params['resultcb'](false);
132
                }
133
                return;
134
            }
135
            list($params['host'], $params['uri']) = $prepared;
136
        }
137
        if ($params['uri'] === '') {
138
            $params['uri'] = '/';
139
        }
140
        $this->lastURL = 'http://' . $params['host'] . $params['uri'];
141
        if (!isset($params['version'])) {
142
            $params['version'] = '1.1';
143
        }
144
        $this->writeln($type . ' ' . $params['uri'] . ' HTTP/' . $params['version']);
145
        if (isset($params['proxy'])) {
146
            if (isset($params['proxy']['auth'])) {
147
                $this->writeln('Proxy-Authorization: basic ' . base64_encode($params['proxy']['auth']['username'] . ':' . $params['proxy']['auth']['password']));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 161 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
148
            }
149
        }
150
        $this->writeln('Host: ' . $params['host']);
151
        if ($this->pool->config->expose->value && !isset($params['headers']['User-Agent'])) {
152
            $this->writeln('User-Agent: phpDaemon/' . Daemon::$version);
153
        }
154
        if (isset($params['cookie']) && sizeof($params['cookie'])) {
155
            $this->writeln('Cookie: ' . http_build_query($params['cookie'], '', '; '));
156
        }
157
        if (isset($params['contentType'])) {
158
            if (!isset($params['headers'])) {
159
                $params['headers'] = [];
160
            }
161
            $params['headers']['Content-Type'] = $params['contentType'];
162
        }
163
        if (isset($params['headers'])) {
164
            $this->customRequestHeaders($params['headers']);
165
        }
166
        if (isset($params['rawHeaders']) && $params['rawHeaders']) {
167
            $this->rawHeaders = [];
168
        }
169
        if (isset($params['chunkcb']) && is_callable($params['chunkcb'])) {
170
            $this->chunkcb = $params['chunkcb'];
171
        }
172
        $this->writeln('');
173
        $this->requests->push($type);
174
        $this->onResponse->push($params['resultcb']);
175
        $this->checkFree();
176
    }
177
178
    /**
179
     * Perform a HEAD request
180
     * @param string $url
181
     * @param array $params
0 ignored issues
show
Documentation introduced by
Should the type for parameter $params not be array|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
182
     */
183
    public function head($url, $params = null)
184
    {
185
        $this->sendRequestHeaders('HEAD', $url, $params);
186
    }
187
188
    /**
189
     * Perform a GET request
190
     * @param string $url
191
     * @param array $params
0 ignored issues
show
Documentation introduced by
Should the type for parameter $params not be array|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
192
     */
193
    public function get($url, $params = null)
194
    {
195
        $this->sendRequestHeaders('GET', $url, $params);
196
    }
197
198
    /**
199
     * @param array $headers
200
     */
201
    protected function customRequestHeaders($headers)
202
    {
203
        foreach ($headers as $key => $item) {
204
            if (is_numeric($key)) {
205
                if (is_string($item)) {
206
                    $this->writeln($item);
207
                } elseif (is_array($item)) {
208
                    $this->writeln($item[0] . ': ' . $item[1]); // @TODO: prevent injections?
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
209
                }
210
            } else {
211
                $this->writeln($key . ': ' . $item);
212
            }
213
        }
214
    }
215
216
    /**
217
     * Perform a POST request
218
     * @param string $url
219
     * @param array $data
220
     * @param array $params
0 ignored issues
show
Documentation introduced by
Should the type for parameter $params not be array|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
221
     */
222
    public function post($url, $data = [], $params = null)
223
    {
224
        foreach ($data as $val) {
225
            if ($val instanceof UploadFile) {
0 ignored issues
show
Bug introduced by
The class PHPDaemon\Clients\HTTP\UploadFile does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
226
                $params['contentType'] = 'multipart/form-data';
227
            }
228
        }
229
        if (!isset($params['contentType'])) {
230
            $params['contentType'] = 'application/x-www-form-urlencoded';
231
        }
232
        if ($params['contentType'] === 'application/x-www-form-urlencoded') {
233
            $body = http_build_query($data, '', '&', PHP_QUERY_RFC3986);
234
        } elseif ($params['contentType'] === 'application/x-json') {
235
            $body = json_encode($data);
236
        } else {
237
            $body = 'Unsupported Content-Type';
238
        }
239
        if (!isset($params['headers'])) {
240
            $params['headers'] = [];
241
        }
242
        $params['headers']['Content-Length'] = mb_orig_strlen($body);
243
        $this->sendRequestHeaders('POST', $url, $params);
244
        $this->write($body);
245
        $this->writeln('');
246
    }
247
248
    /**
249
     * Get body
250
     * @return string
251
     */
252
    public function getBody()
253
    {
254
        return $this->body;
255
    }
256
257
    /**
258
     * Get headers
259
     * @return array
260
     */
261
    public function getHeaders()
262
    {
263
        return $this->headers;
264
    }
265
266
    /**
267
     * Get header
268
     * @param  string $name Header name
269
     * @return string
270
     */
271
    public function getHeader($name)
272
    {
273
        $k = 'HTTP_' . strtoupper(strtr($name, Generic::$htr));
274
        return isset($this->headers[$k]) ? $this->headers[$k] : null;
275
    }
276
277
    /**
278
     * Called when new data received
279
     */
280
    public function onRead()
281
    {
282
        if ($this->state === self::STATE_BODY) {
283
            goto body;
284
        }
285
        if ($this->reqType === null) {
286
            if ($this->requests->isEmpty()) {
287
                $this->finish();
288
                return;
289
            }
290
            $this->reqType = $this->requests->shift();
291
        }
292
        while (($line = $this->readLine()) !== null) {
293
            if ($line !== '') {
294
                if ($this->rawHeaders !== null) {
295
                    $this->rawHeaders[] = $line;
296
                }
297
            } else {
298
                if (isset($this->headers['HTTP_CONTENT_LENGTH'])) {
299
                    $this->contentLength = (int)$this->headers['HTTP_CONTENT_LENGTH'];
300
                } else {
301
                    $this->contentLength = -1;
302
                }
303 View Code Duplication
                if (isset($this->headers['HTTP_TRANSFER_ENCODING'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
304
                    $e = explode(', ', strtolower($this->headers['HTTP_TRANSFER_ENCODING']));
305
                    $this->chunked = in_array('chunked', $e, true);
306
                } else {
307
                    $this->chunked = false;
308
                }
309 View Code Duplication
                if (isset($this->headers['HTTP_CONNECTION'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
310
                    $e = explode(', ', strtolower($this->headers['HTTP_CONNECTION']));
311
                    $this->keepalive = in_array('keep-alive', $e, true);
312
                }
313
                if (isset($this->headers['HTTP_CONTENT_TYPE'])) {
314
                    parse_str('type=' . strtr($this->headers['HTTP_CONTENT_TYPE'], [';' => '&', ' ' => '']), $p);
315
                    $this->contentType = $p['type'];
316
                    if (isset($p['charset'])) {
317
                        $this->charset = strtolower($p['charset']);
318
                    }
319
                }
320
                if ($this->contentLength === -1 && !$this->chunked && !$this->keepalive) {
321
                    $this->eofTerminated = true;
322
                }
323
                if ($this->reqType === 'HEAD') {
324
                    $this->requestFinished();
325
                } else {
326
                    $this->state = self::STATE_BODY;
327
                }
328
                break;
329
            }
330
            if ($this->state === self::STATE_ROOT) {
331
                $this->headers['STATUS'] = $line;
332
                $e = explode(' ', $this->headers['STATUS']);
333
                $this->responseCode = isset($e[1]) ? (int)$e[1] : 0;
334
                $this->state = self::STATE_HEADERS;
335
            } elseif ($this->state === self::STATE_HEADERS) {
336
                $e = explode(': ', $line);
337
338
                if (isset($e[1])) {
339
                    $k = 'HTTP_' . strtoupper(strtr($e[0], Generic::$htr));
340
                    if ($k === 'HTTP_SET_COOKIE') {
341
                        parse_str(strtr($e[1], [';' => '&', ' ' => '']), $p);
342
                        if (sizeof($p)) {
343
                            $this->cookie[$k = key($p)] =& $p;
344
                            $p['value'] = $p[$k];
345
                            unset($p[$k], $p);
346
                        }
347
                    }
348
                    if (isset($this->headers[$k])) {
349
                        if (is_array($this->headers[$k])) {
350
                            $this->headers[$k][] = $e[1];
351
                        } else {
352
                            $this->headers[$k] = [$this->headers[$k], $e[1]];
353
                        }
354
                    } else {
355
                        $this->headers[$k] = $e[1];
356
                    }
357
                }
358
            }
359
        }
360
        if ($this->state !== self::STATE_BODY) {
361
            return; // not enough data yet
362
        }
363
        body:
364
        if ($this->eofTerminated) {
365
            $body = $this->readUnlimited();
366
            if ($this->chunkcb) {
367
                $func = $this->chunkcb;
368
                $func($body);
369
            }
370
            $this->body .= $body;
371
            return;
372
        }
373
        if ($this->chunked) {
374
            chunk:
375
            if ($this->curChunkSize === null) { // outside of chunk
376
                $l = $this->readLine();
377
                if ($l === '') { // skip empty line
378
                    goto chunk;
379
                }
380
                if ($l === null) {
381
                    return; // not enough data yet
382
                }
383
                if (!ctype_xdigit($l)) {
384
                    $this->protocolError = __LINE__;
385
                    $this->finish(); // protocol error
386
                    return;
387
                }
388
                $this->curChunkSize = hexdec($l);
0 ignored issues
show
Documentation Bug introduced by
It seems like hexdec($l) can also be of type double. However, the property $curChunkSize is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
389
            }
390
            if ($this->curChunkSize !== null) {
391
                if ($this->curChunkSize === 0) {
392
                    if ($this->readLine() === '') {
393
                        $this->requestFinished();
394
                        return;
395
                    } else { // protocol error
396
                        $this->protocolError = __LINE__;
397
                        $this->finish();
398
                        return;
399
                    }
400
                }
401
                $n = $this->curChunkSize - mb_orig_strlen($this->curChunk);
402
                $this->curChunk .= $this->read($n);
403
                if ($this->curChunkSize <= mb_orig_strlen($this->curChunk)) {
404
                    if ($this->chunkcb) {
405
                        $func = $this->chunkcb;
406
                        $func($this->curChunk);
407
                    }
408
                    $this->body .= $this->curChunk;
409
                    $this->curChunkSize = null;
410
                    $this->curChunk = '';
411
                    goto chunk;
412
                }
413
            }
414
        } else {
415
            $body = $this->read($this->contentLength - mb_orig_strlen($this->body));
416
            if ($this->chunkcb) {
417
                $func = $this->chunkcb;
418
                $func($body);
419
            }
420
            $this->body .= $body;
421
            if (($this->contentLength !== -1) && (mb_orig_strlen($this->body) >= $this->contentLength)) {
422
                $this->requestFinished();
423
            }
424
        }
425
    }
426
427
    /**
428
     * Called when connection finishes
429
     */
430
    public function onFinish()
431
    {
432
        if ($this->eofTerminated) {
433
            $this->requestFinished();
434
            $this->onResponse->executeAll($this, false);
435
            parent::onFinish();
436
            return;
437
        }
438
        if ($this->protocolError) {
439
            $this->onResponse->executeAll($this, false);
440
        } else {
441
            if (($this->state !== self::STATE_ROOT) && !$this->onResponse->isEmpty()) {
442
                $this->requestFinished();
443
            }
444
        }
445
        parent::onFinish();
446
    }
447
448
    /**
449
     * Called when request is finished
450
     */
451
    protected function requestFinished()
452
    {
453
        $this->onResponse->executeOne($this, true);
454
        $this->state = self::STATE_ROOT;
455
        $this->contentLength = -1;
456
        $this->curChunkSize = null;
457
        $this->chunked = false;
458
        $this->eofTerminated = false;
459
        $this->headers = [];
460
        $this->rawHeaders = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $rawHeaders.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
461
        $this->contentType = null;
462
        $this->charset = null;
463
        $this->body = '';
464
        $this->responseCode = 0;
465
        $this->reqType = null;
466
        if (!$this->keepalive) {
467
            $this->finish();
468
        }
469
        $this->checkFree();
470
    }
471
}
472