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.
Completed
Pull Request — master (#3)
by Cees-Jan
01:54
created

AsyncClient::__construct()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 63
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 63
ccs 12
cts 12
cp 1
rs 9.4347
c 0
b 0
f 0
cc 3
eloc 28
nc 1
nop 2
crap 3

How to fix   Long Method   

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 declare(strict_types=1);
2
3
namespace ApiClients\Client\Pusher;
4
5
use React\Dns\Resolver\Resolver;
6
use React\EventLoop\LoopInterface;
7
use Rx\Disposable\CallbackDisposable;
8
use Rx\Observable;
9
use Rx\ObserverInterface;
10
use Rx\Scheduler;
11
use Rx\Websocket\Client as WebsocketClient;
12
use Rx\Websocket\MessageSubject;
13
use Throwable;
14
15
final class AsyncClient
16
{
17
    const NO_ACTIVITY_TIMEOUT = 120;
18
    const NO_PING_RESPONSE_TIMEOUT = 30;
19
20
    protected $noActivityTimeout = self::NO_ACTIVITY_TIMEOUT;
21
22
    /**
23
     * @var LoopInterface
24
     */
25
    protected $loop;
26
27
    /**
28
     * @var Observable\RefCountObservable
29
     */
30
    protected $client;
31
32
    /**
33
     * @var Observable\AnonymousObservable
34
     */
35
    protected $messages;
36
37
    /**
38
     * @var MessageSubject
39
     */
40
    protected $sendSubject;
41
42
    /**
43
     * @var array
44
     */
45
    protected $channels = [];
46
47
    /**
48
     * @var int
49
     */
50
    protected $delay = 200;
51
52
    /**
53
     * @param LoopInterface $loop
54
     * @param string $app Application ID
55
     * @param Resolver $resolver Optional DNS resolver
56
     * @return AsyncClient
57
     */
58 3
    public static function create(LoopInterface $loop, string $app, Resolver $resolver = null): AsyncClient
59
    {
60
        try {
61
            Scheduler::setAsyncFactory(function () use ($loop) {
62
                return new Scheduler\EventLoopScheduler($loop);
0 ignored issues
show
Documentation introduced by
$loop is of type object<React\EventLoop\LoopInterface>, but the function expects a callable.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
63 3
            });
64
        } catch (Throwable $t) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
65
        }
66
67 3
        return new self(
68
            $loop,
69 3
            new WebsocketClient(
70 3
                ApiSettings::createUrl($app),
71 3
                false,
72 3
                [],
73
                $loop,
74
                $resolver
75
            )
76
        );
77
    }
78
79
    /**
80
     * @internal
81
     */
82 3
    public function __construct(LoopInterface $loop, WebsocketClient $client)
83
    {
84 3
        $this->loop = $loop;
85 3
        $this->messages = $client
86
            // Save this subject for sending stuff
87
            ->do(function (MessageSubject $ms) {
88
                $this->sendSubject = $ms;
89
90
                // Resubscribe to an channels we where subscribed to when disconnected
91
                foreach ($this->channels as $channel => $_) {
92
                    $this->subscribeOnChannel($channel);
93
                }
94 3
            })
95
96
            // Make sure if there is a disconnect or something
97
            // that we unset the sendSubject
98
            ->finally(function () {
99
                $this->sendSubject = null;
100 3
            })
101
102
            ->flatMap(function (MessageSubject $ms) {
103
                return $ms;
104 3
            })
105
106
            // This is the ping/timeout functionality
107
            ->flatMapLatest(function ($x) {
108
                // this Observable emits the current value immediately
109
                // if another value comes along, this all gets disposed (because we are using flatMapLatest)
110
                // before the timeouts start get triggered
111
                return Observable::never()
112
                    ->timeout($this->noActivityTimeout * 1000)
113
                    ->catch(function () use ($x) {
114
                        // ping (do something that causes incoming stream to get a message)
115
                        $this->send(['event' => 'pusher:ping']);
116
                        // this timeout will actually timeout with a TimeoutException - causing
117
                        //   everything above this to dispose
118
                        return Observable::never()->timeout(self::NO_PING_RESPONSE_TIMEOUT * 1000);
119
                    })
120
                    ->startWith($x);
121 3
            })
122
123
            // Handle connection level errors
124
            ->retryWhen(function (Observable $errors) {
125
                return $errors->flatMap(function (Throwable $throwable) {
126
                    return $this->handleLowLevelError($throwable);
127
                });
128 3
            })
129
130
            // Decode JSON
131 3
            ->_ApiClients_jsonDecode()
132
133
            // Deal with connection established messages
134
            ->map(function (array $message) {
135
                $event = Event::createFromMessage($message);
136
137
                if ($event->getEvent() === 'pusher:connection_established') {
138
                    $this->setActivityTimeout($event);
139
                }
140
141
                return $event;
142 3
            })
143 3
            ->share();
144 3
    }
145
146
    /**
147
     * Listen on a channel
148
     *
149
     * @param string $channel Channel to listen on
150
     * @return Observable
151
     */
152
    public function channel(string $channel): Observable
153
    {
154
        if (isset($this->channels[$channel])) {
155
            return $this->channels[$channel];
156
        }
157
158
        $channelMessages = $this->messages->filter(function (Event $event) use ($channel) {
159
            return $event->getChannel() !== '' && $event->getChannel() === $channel;
160
        });
161
162
        $events = Observable::create(function (
163
            ObserverInterface $observer
164
        ) use (
165
            $channel,
166
            $channelMessages
167
        ) {
168
            $subscription = $channelMessages
169
                ->filter(function (Event $event) {
170
                    return $event->getEvent() !== 'pusher_internal:subscription_succeeded';
171
                })
172
                ->subscribe($observer);
0 ignored issues
show
Documentation introduced by
$observer is of type object<Rx\ObserverInterface>, but the function expects a callable|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
173
174
            $this->subscribeOnChannel($channel);
175
176
            return new CallbackDisposable(function () use ($channel, $subscription) {
177
                $this->send(['event' => 'pusher:unsubscribe', 'data' => ['channel' => $channel]]);
178
                $subscription->dispose();
179
                unset($this->channels[$channel]);
180
            });
181
        });
182
183
        $this->channels[$channel] = $events->share();
184
        return $this->channels[$channel];
185
    }
186
187
    /**
188
     * Send a message through the client
189
     *
190
     * @param array $message Message to send, will be json encoded
191
     *
192
     * @return A bool indicating whether or not the connection was active
193
     *         and the given message has been pass onto the connection.
194
     */
195
    public function send(array $message): bool
196
    {
197
        if ($this->sendSubject ===  null) {
198
            return false;
199
        }
200
201
        $this->sendSubject->onNext(json_encode($message));
202
        return true;
203
    }
204
205
    private function handleLowLevelError(Throwable $throwable)
0 ignored issues
show
Unused Code introduced by
The parameter $throwable is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
206
    {
207
        $this->delay *= 2;
208
        return Observable::timer($this->delay);
209
    }
210
211
    /**
212
     * @param string $channel
213
     */
214
    private function subscribeOnChannel(string $channel)
215
    {
216
        $this->send(['event' => 'pusher:subscribe', 'data' => ['channel' => $channel]]);
217
    }
218
219
220
    /**
221
     * Get connection activity timeout from connection established event
222
     *
223
     * @param Event $event
224
     */
225
    private function setActivityTimeout(Event $event)
226
    {
227
        $data = $event->getData();
228
229
        // No activity_timeout found on event
230
        if (!isset($data['activity_timeout'])) {
231
            return;
232
        }
233
234
        // activity_timeout holds zero or invalid value (we don't want to hammer Pusher)
235
        if ((int)$data['activity_timeout'] <= 0) {
236
            return;
237
        }
238
239
        $this->noActivityTimeout = (int)$data['activity_timeout'];
240
    }
241
}
242