StreamReader::processError()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 0
cts 8
cp 0
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
crap 6
1
<?php declare(strict_types = 1);
2
3
namespace PeeHaa\AsyncTwitter\Api\Client;
4
5
use Amp\Artax\Notify;
6
use Amp\Deferred;
7
use Amp\Promise;
8
use ExceptionalJSON\DecodeErrorException;
9
use PeeHaa\AsyncTwitter\Api\Client\Exception\StreamFailureException;
10
use PeeHaa\AsyncTwitter\Api\Client\Exception\StreamOpenFailureException;
11
use PeeHaa\AsyncTwitter\Api\StatusStream;
12
13
class StreamReader
14
{
15
    /**
16
     * @uses processResponseHeaders
17
     * @uses processBodyData
18
     * @uses processResponseComplete
19
     * @uses processError
20
     */
21
    private static $progressHandlers = [
22
        Notify::RESPONSE_HEADERS   => 'processResponseHeaders',
23
        Notify::RESPONSE_BODY_DATA => 'processBodyData',
24
        Notify::RESPONSE           => 'processResponseComplete',
25
        Notify::ERROR              => 'processError',
26
    ];
27
28
    /**
29
     * @var StatusStream
30
     */
31
    private $stream;
32
33
    private $openDeferred;
34
    private $inflateCtx;
35
    private $rawDataBuffer = '';
36
37
    public function __construct()
38
    {
39
        $this->openDeferred = new Deferred;
40
    }
41
42
    private function processBodyData(string $data)
43
    {
44
        if ($this->stream === null) {
45
            return;
46
        }
47
48
        /** @noinspection PhpUndefinedFunctionInspection */
49
        $this->rawDataBuffer .= $this->inflateCtx !== null
50
            ? \inflate_add($this->inflateCtx, $data)
51
            : $data;
52
53
        while (false !== $pos = \strpos($this->rawDataBuffer, "\r\n")) {
54
            if ($pos > 0) {
55
                try {
56
                    $this->stream->update(\json_try_decode(\substr($this->rawDataBuffer, 0, $pos), true));
57
                } catch (DecodeErrorException $e) {
58
                    $this->stream->fail(new StreamFailureException('Error decoding stream data', 0, $e));
59
                    $this->inflateCtx = $this->stream = null;
60
                    return;
61
                }
62
            }
63
64
            $this->rawDataBuffer = (string)\substr($this->rawDataBuffer, $pos + 2);
65
        }
66
    }
67
68
    private function processResponseHeaders(array $info)
69
    {
70
        static $zlibEncodingMap = [
71
            'gzip'    => ZLIB_ENCODING_GZIP,
72
            'x-gzip'  => ZLIB_ENCODING_GZIP,    // recommended for compatibility by MDN
73
            'deflate' => ZLIB_ENCODING_DEFLATE,
74
        ];
75
76
        $status = (int)($info['status'] ?? -1);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 2 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
77
        $headers = (array)($info['headers'] ?? []);
78
79
        if ($status !== 200) {
80
            $this->openDeferred->fail(new StreamOpenFailureException("Server responded with HTTP status {$status}"));
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $status instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
81
        }
82
83
        $encoding = 'identity';
84
85
        foreach ($headers as $name => $values) {
86
            if (\strtolower($name) !== 'content-encoding') {
87
                continue;
88
            }
89
90
            $encoding = \strtolower($values[0] ?? 'identity');
91
        }
92
93
        if ($encoding !== 'identity') {
94
            if (!isset($zlibEncodingMap[$encoding])) {
95
                $this->openDeferred->fail(
96
                    new StreamOpenFailureException("Server is using an encoding format I don't understand: {$encoding}")
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $encoding instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
97
                );
98
            }
99
100
            /** @noinspection PhpUndefinedFunctionInspection */
101
            $this->inflateCtx = \inflate_init($zlibEncodingMap[$encoding]);
102
        }
103
104
        $this->stream = new StatusStream;
105
106
        $this->openDeferred->succeed($this->stream);
0 ignored issues
show
Bug introduced by
The method succeed() does not seem to exist on object<Amp\Deferred>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
107
    }
108
109
    private function processError(\Throwable $error)
110
    {
111
        if ($this->stream === null) {
112
            return;
113
        }
114
115
        $this->stream->fail(new StreamFailureException("HTTP request error", 0, $error));
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal HTTP request error does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
116
        $this->inflateCtx = $this->stream = null;
117
    }
118
119
    private function processResponseComplete()
120
    {
121
        if ($this->stream === null) {
122
            return;
123
        }
124
125
        $this->stream->end();
126
        $this->inflateCtx = $this->stream = null;
127
    }
128
129
    public function awaitStreamOpen(): Promise
130
    {
131
        return $this->openDeferred->promise();
132
    }
133
134
    public function onProgress(array $data)
135
    {
136
        if (!isset(self::$progressHandlers[$data[0]])) {
137
            return;
138
        }
139
140
        \call_user_func([$this, self::$progressHandlers[$data[0]]], $data[1]);
141
    }
142
}
143