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
02:48
created

AsyncClient::subscribeOnChannel()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
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 RuntimeException;
8
use Rx\Disposable\CallbackDisposable;
9
use Rx\Observable;
10
use Rx\ObserverInterface;
11
use Rx\Scheduler;
12
use Rx\Websocket\Client as WebsocketClient;
13
use Rx\Websocket\MessageSubject;
14
use Rx\Websocket\WebsocketErrorException;
15
use Throwable;
16
use function React\Promise\reject;
17
use function React\Promise\resolve;
18
19
final class AsyncClient
20
{
21
    const DEFAULT_DELAY = 200;
22
    const NO_ACTIVITY_TIMEOUT = 120;
23
    const NO_PING_RESPONSE_TIMEOUT = 30;
24
25
    protected $noActivityTimeout = self::NO_ACTIVITY_TIMEOUT;
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 = self::DEFAULT_DELAY;
51
52
    /**
53
     * @internal
54
     */
55 5
    public function __construct(Observable $client)
56
    {
57 5
        $this->messages = $client
58
            // Save this subject for sending stuff
59
            ->do(function (MessageSubject $ms) {
60
                $this->sendSubject = $ms;
61
62
                // Resubscribe to an channels we where subscribed to when disconnected
63
                foreach ($this->channels as $channel => $_) {
64
                    $this->subscribeOnChannel($channel);
65
                }
66 5
            })
67
68
            // Make sure if there is a disconnect or something
69
            // that we unset the sendSubject
70
            ->finally(function () {
71 2
                $this->sendSubject = null;
72 5
            })
73
74
            ->flatMap(function (MessageSubject $ms) {
75
                return $ms;
76 5
            })
77
78
            // This is the ping/timeout functionality
79
            ->flatMapLatest(function ($x) {
80
                // this Observable emits the current value immediately
81
                // if another value comes along, this all gets disposed (because we are using flatMapLatest)
82
                // before the timeouts start get triggered
83
                return Observable::never()
84
                    ->timeout($this->noActivityTimeout * 1000)
85
                    ->catch(function () use ($x) {
86
                        // ping (do something that causes incoming stream to get a message)
87
                        $this->send(['event' => 'pusher:ping']);
88
                        // this timeout will actually timeout with a TimeoutException - causing
89
                        //   everything above this to dispose
90
                        return Observable::never()->timeout(self::NO_PING_RESPONSE_TIMEOUT * 1000);
91
                    })
92
                    ->startWith($x);
93 5
            })
94
95
            // Decode JSON
96 5
            ->_ApiClients_jsonDecode()
97
98
            // Deal with connection established messages
99
            ->flatMap(function (array $message) {
100
                $this->delay = self::DEFAULT_DELAY;
101
102
                $event = Event::createFromMessage($message);
103
104
                if ($event->getEvent() === 'pusher:error') {
105
                    return Observable::fromPromise(reject(new PusherErrorException($event->getData()['message'], $event->getData()['code'])));
106
                }
107
108
                if ($event->getEvent() === 'pusher:connection_established') {
109
                    $this->setActivityTimeout($event);
110
                }
111
112
                return Observable::fromPromise(resolve($event));
113 5
            })
114
115
            // Handle connection level errors
116
            ->retryWhen(function (Observable $errors) {
117
                return $errors->flatMap(function (Throwable $throwable) {
118 2
                    return $this->handleLowLevelError($throwable);
119 2
                });
120 5
            })
121
122
        // Share client
123 5
        ->share();
124 5
    }
125
126
    /**
127
     * @param  LoopInterface $loop
128
     * @param  string        $app      Application ID
129
     * @param  Resolver      $resolver Optional DNS resolver
130
     * @return AsyncClient
131
     */
132 4
    public static function create(LoopInterface $loop, string $app, Resolver $resolver = null): AsyncClient
133
    {
134
        try {
135
            Scheduler::setAsyncFactory(function () use ($loop) {
136 1
                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...
137 4
            });
138 3
        } catch (Throwable $t) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
139
        }
140
141 4
        return new self(
142 4
            new WebsocketClient(
143 4
                ApiSettings::createUrl($app),
144 4
                false,
145 4
                [],
146
                $loop,
147 4
                $resolver
148
            )
149
        );
150
    }
151
152
    /**
153
     * Listen on a channel.
154
     *
155
     * @param  string     $channel Channel to listen on
156
     * @return Observable
157
     */
158 2
    public function channel(string $channel): Observable
159
    {
160 2
        if (isset($this->channels[$channel])) {
161
            return $this->channels[$channel];
162
        }
163
164
        // Ensure we only get messages for the given channel
165
        $channelMessages = $this->messages->filter(function (Event $event) use ($channel) {
166
            return $event->getChannel() !== '' && $event->getChannel() === $channel;
167 2
        });
168
169
        $events = Observable::create(function (
170
            ObserverInterface $observer
171
        ) use (
172 2
            $channel,
173 2
            $channelMessages
174
        ) {
175
            $subscription = $channelMessages
176
                ->filter(function (Event $event) {
177
                    return $event->getEvent() !== 'pusher_internal:subscription_succeeded';
178 2
                })
179 2
                ->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...
180
181 2
            $this->subscribeOnChannel($channel);
182
183 2
            return new CallbackDisposable(function () use ($channel, $subscription) {
184
                // Send unsubscribe event
185
                $this->send(['event' => 'pusher:unsubscribe', 'data' => ['channel' => $channel]]);
186
                // Dispose our own subscription to messages
187
                $subscription->dispose();
188
                // Remove our channel from the channel list so we don't resubscribe in case we reconnect
189
                unset($this->channels[$channel]);
190 2
            });
191 2
        });
192
193
        // Share stream amount subscribers to this channel
194 2
        $this->channels[$channel] = $events->share();
195
196 2
        return $this->channels[$channel];
197
    }
198
199
    /**
200
     * Send a message through the client.
201
     *
202
     * @param array $message Message to send, will be json encoded
203
     *
204
     * @return A bool indicating whether or not the connection was active
205
     *           and the given message has been pass onto the connection.
206
     */
207 2
    public function send(array $message): bool
208
    {
209
        // Don't send messages when we aren't connected
210 2
        if ($this->sendSubject ===  null) {
211 2
            return false;
212
        }
213
214
        $this->sendSubject->onNext(json_encode($message));
215
216
        return true;
217
    }
218
219
    /**
220
     *  Handle errors as described at https://pusher.com/docs/pusher_protocol#error-codes.
221
     */
222 2
    private function handleLowLevelError(Throwable $throwable)
223
    {
224 2
        if (!($throwable instanceof WebsocketErrorException) && !($throwable instanceof RuntimeException) && !($throwable instanceof PusherErrorException)) {
225
            return Observable::fromPromise(reject($throwable));
226
        }
227
228 2
        $code = $throwable->getCode();
229 2
        $pusherError = ($throwable instanceof WebsocketErrorException || $throwable instanceof PusherErrorException);
230
231
        // Errors 4000-4099, don't retry connecting
232 2
        if ($pusherError && $code >= 4000 && $code <= 4099) {
233
            return Observable::fromPromise(reject($throwable));
234
        }
235
236
        // Errors 4100-4199 reconnect after 1 or more seconds, we do it after 1.001 second
237 2
        if ($pusherError && $code >= 4100 && $code <= 4199) {
238
            return Observable::timer(1001);
239
        }
240
241
        // Errors 4200-4299 connection closed by Pusher, reconnect immediately, we wait 0.001 second
242 2
        if ($pusherError && $code >= 4200 && $code <= 4299) {
243
            return Observable::timer(1);
244
        }
245
246 2
        $this->delay *= 2;
247
248 2
        return Observable::timer($this->delay);
249
    }
250
251
    /**
252
     * @param string $channel
253
     */
254 2
    private function subscribeOnChannel(string $channel)
255
    {
256 2
        $this->send(['event' => 'pusher:subscribe', 'data' => ['channel' => $channel]]);
257 2
    }
258
259
    /**
260
     * Get connection activity timeout from connection established event.
261
     *
262
     * @param Event $event
263
     */
264
    private function setActivityTimeout(Event $event)
265
    {
266
        $data = $event->getData();
267
268
        // No activity_timeout found on event
269
        if (!isset($data['activity_timeout'])) {
270
            return;
271
        }
272
273
        // activity_timeout holds zero or invalid value (we don't want to hammer Pusher)
274
        if ((int)$data['activity_timeout'] <= 0) {
275
            return;
276
        }
277
278
        $this->noActivityTimeout = (int)$data['activity_timeout'];
279
    }
280
}
281