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
Push — master ( ebd3a0...9be4f1 )
by Cees-Jan
02:05
created

AsyncClient::create()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3.0884

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 11
cts 14
cp 0.7856
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 15
nc 4
nop 3
crap 3.0884
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(
106
                        new PusherErrorException($event->getData()['message'], $event->getData()['code'])
107
                    ));
108
                }
109
110
                if ($event->getEvent() === 'pusher:connection_established') {
111
                    $this->setActivityTimeout($event);
112
                }
113
114
                return Observable::fromPromise(resolve($event));
115 5
            })
116
117
            // Handle connection level and Pusher procotol errors
118
            ->retryWhen(function (Observable $errors) {
119
                return $errors->flatMap(function (Throwable $throwable) {
120 2
                    return $this->handleLowLevelError($throwable);
121 2
                });
122 5
            })
123
124
        // Share client
125 5
        ->share();
126 5
    }
127
128
    /**
129
     * @param  LoopInterface $loop
130
     * @param  string        $app      Application ID
131
     * @param  Resolver      $resolver Optional DNS resolver
132
     * @return AsyncClient
133
     */
134 4
    public static function create(LoopInterface $loop, string $app, Resolver $resolver = null): AsyncClient
135
    {
136
        try {
137
            Scheduler::setAsyncFactory(function () use ($loop) {
138 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...
139 4
            });
140 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...
141
        }
142
143
        try {
144
            Scheduler::setDefaultFactory(function () {
145
                return Scheduler::getImmediate();
146 4
            });
147
        } catch (Throwable $t) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
148
        }
149
150 4
        return new self(
151 4
            new WebsocketClient(
152 4
                ApiSettings::createUrl($app),
153 4
                false,
154 4
                [],
155
                $loop,
156 4
                $resolver
157
            )
158
        );
159
    }
160
161
    /**
162
     * Listen on a channel.
163
     *
164
     * @param  string     $channel Channel to listen on
165
     * @return Observable
166
     */
167 2
    public function channel(string $channel): Observable
168
    {
169 2
        if (isset($this->channels[$channel])) {
170
            return $this->channels[$channel];
171
        }
172
173
        // Ensure we only get messages for the given channel
174
        $channelMessages = $this->messages->filter(function (Event $event) use ($channel) {
175
            return $event->getChannel() !== '' && $event->getChannel() === $channel;
176 2
        });
177
178
        $events = Observable::create(function (
179
            ObserverInterface $observer
180
        ) use (
181 2
            $channel,
182 2
            $channelMessages
183
        ) {
184
            $subscription = $channelMessages
185
                ->filter(function (Event $event) {
186
                    return $event->getEvent() !== 'pusher_internal:subscription_succeeded';
187 2
                })
188 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...
189
190 2
            $this->subscribeOnChannel($channel);
191
192 2
            return new CallbackDisposable(function () use ($channel, $subscription) {
193
                // Send unsubscribe event
194
                $this->send(['event' => 'pusher:unsubscribe', 'data' => ['channel' => $channel]]);
195
                // Dispose our own subscription to messages
196
                $subscription->dispose();
197
                // Remove our channel from the channel list so we don't resubscribe in case we reconnect
198
                unset($this->channels[$channel]);
199 2
            });
200 2
        });
201
202
        // Share stream amount subscribers to this channel
203 2
        $this->channels[$channel] = $events->share();
204
205 2
        return $this->channels[$channel];
206
    }
207
208
    /**
209
     * Send a message through the client.
210
     *
211
     * @param array $message Message to send, will be json encoded
212
     *
213
     * @return A bool indicating whether or not the connection was active
214
     *           and the given message has been pass onto the connection.
215
     */
216 2
    public function send(array $message): bool
217
    {
218
        // Don't send messages when we aren't connected
219 2
        if ($this->sendSubject ===  null) {
220 2
            return false;
221
        }
222
223
        $this->sendSubject->onNext(json_encode($message));
224
225
        return true;
226
    }
227
228
    /**
229
     *  Handle errors as described at https://pusher.com/docs/pusher_protocol#error-codes.
230
     */
231 2
    private function handleLowLevelError(Throwable $throwable)
232
    {
233 2
        if (!($throwable instanceof WebsocketErrorException) &&
234 2
            !($throwable instanceof RuntimeException) &&
235 2
            !($throwable instanceof PusherErrorException)
236
        ) {
237
            return Observable::fromPromise(reject($throwable));
238
        }
239
240 2
        $code = $throwable->getCode();
241 2
        $pusherError = ($throwable instanceof WebsocketErrorException || $throwable instanceof PusherErrorException);
242
243
        // Errors 4000-4099, don't retry connecting
244 2
        if ($pusherError && $code >= 4000 && $code <= 4099) {
245
            return Observable::fromPromise(reject($throwable));
246
        }
247
248
        // Errors 4100-4199 reconnect after 1 or more seconds, we do it after 1.001 second
249 2
        if ($pusherError && $code >= 4100 && $code <= 4199) {
250
            return Observable::timer(1001);
251
        }
252
253
        // Errors 4200-4299 connection closed by Pusher, reconnect immediately, we wait 0.001 second
254 2
        if ($pusherError && $code >= 4200 && $code <= 4299) {
255
            return Observable::timer(1);
256
        }
257
258 2
        $this->delay *= 2;
259
260 2
        return Observable::timer($this->delay);
261
    }
262
263
    /**
264
     * @param string $channel
265
     */
266 2
    private function subscribeOnChannel(string $channel)
267
    {
268 2
        $this->send(['event' => 'pusher:subscribe', 'data' => ['channel' => $channel]]);
269 2
    }
270
271
    /**
272
     * Get connection activity timeout from connection established event.
273
     *
274
     * @param Event $event
275
     */
276
    private function setActivityTimeout(Event $event)
277
    {
278
        $data = $event->getData();
279
280
        // No activity_timeout found on event
281
        if (!isset($data['activity_timeout'])) {
282
            return;
283
        }
284
285
        // activity_timeout holds zero or invalid value (we don't want to hammer Pusher)
286
        if ((int)$data['activity_timeout'] <= 0) {
287
            return;
288
        }
289
290
        $this->noActivityTimeout = (int)$data['activity_timeout'];
291
    }
292
}
293