Completed
Push — develop ( 2bfb76...2f90e1 )
by Kirill
04:03
created

GitterRoomListenCommand   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 168
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 15

Importance

Changes 9
Bugs 0 Features 1
Metric Value
wmc 11
lcom 1
cbo 15
dl 0
loc 168
rs 9.1666
c 9
b 0
f 1

5 Methods

Rating   Name   Duplication   Size   Complexity  
B handle() 0 31 3
A auth() 0 12 1
B listen() 0 40 2
B onMessageFallback() 0 26 2
A onMessage() 0 17 3
1
<?php
2
/**
3
 * This file is part of GitterBot package.
4
 *
5
 * @author Serafim <[email protected]>
6
 * @date 26.01.2016 4:57
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
namespace App\Console\Commands;
12
13
use App\Gitter\Extensions\MiddlewareBuilder;
14
use App\Message;
15
use App\Room;
16
use App\User;
17
use Carbon\Carbon;
18
use Gitter\Client;
19
use Gitter\Iterators\PromiseIterator\Controls;
20
use Gitter\Models\Message as GitterMessage;
21
use Gitter\Models\Room as GitterRoom;
22
use Gitter\Models\User as GitterUser;
23
use Illuminate\Contracts\Config\Repository;
24
use Illuminate\Contracts\Container\Container;
25
use React\EventLoop\LoopInterface;
26
27
28
/**
29
 * Class GitterRoomListenCommand
30
 * @package App\Console\Commands
31
 *
32
 * Прослушивание сообщений требуемой комнаты
33
 */
34
class GitterRoomListenCommand extends AbstractCommand
35
{
36
    /**
37
     * @var string
38
     */
39
    protected $signature = 'gitter:listen {room}';
40
41
    /**
42
     * @var string
43
     */
44
    protected $description = 'Listen gitter room';
45
46
    /**
47
     * Execute the console command.
48
     *
49
     * @param Repository $config
50
     * @param Container $container
51
     *
52
     * @return mixed
53
     */
54
    public function handle(Repository $config, Container $container)
55
    {
56
        /** @var Client $client */
57
        $client = $this->createClient($container, $config->get('gitter.token'));
58
59
        $this->auth($client, function (User $user) use ($client) {
0 ignored issues
show
Unused Code introduced by
The parameter $user 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...
60
61
            $this->findRoom($client, $this->argument('room'), function (GitterRoom $room) use ($client) {
0 ignored issues
show
Bug introduced by
It seems like $this->argument('room') targeting Illuminate\Console\Command::argument() can also be of type array; however, App\Console\Commands\AbstractCommand::findRoom() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
62
                try {
63
                    $this->listen($room, true);
64
65
                    $client->onChangeFallbackMode(function($state) use ($room) {
66
                        if ($state) {
67
                            $room->sendMessage('_Подключение к Gitter Stream API восстановлено_');
68
                        } else {
69
                            $room->sendMessage('_Подключение к Gitter Stream API потеряно. Слоупок mode enabled._');
70
                        }
71
                    });
72
73
                } catch (\Throwable $e) {
74
                    $this->error($e->getMessage());
75
                }
76
            });
77
78
        });
79
80
81
        /** @var LoopInterface $loop */
82
        $loop = $container->make(LoopInterface::class);
83
        $loop->run();
84
    }
85
86
    /**
87
     * @param Client $client
88
     * @param \Closure $callback
89
     */
90
    protected function auth(Client $client, \Closure $callback)
91
    {
92
        GitterUser::current($client)
93
            ->then(function (GitterUser $gitterUser) use ($callback) {
94
                $user = User::make($gitterUser);
95
                \Auth::setUser($user);
96
97
                $callback($user);
98
            }, function(\Throwable $e) {
99
                $this->onError($e);
0 ignored issues
show
Bug introduced by
The method onError() does not exist on App\Console\Commands\GitterRoomListenCommand. Did you maybe mean ignoreValidationErrors()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
100
            });
101
    }
102
103
    /**
104
     * @param GitterRoom $gitter
105
     * @param bool $startup
106
     * @return $this
107
     */
108
    protected function listen(GitterRoom $gitter, $startup = false)
109
    {
110
        /** @var Room $room */
111
        $room = Room::make($gitter, function (Room $room) {
112
            $this->call('gitter:sync', [
113
                'room'       => $room->gitter_id,
114
                '--users'    => true,
115
                '--messages' => true,
116
            ]);
117
        });
118
119
        /** @var LoopInterface $loop */
120
        $loop = app(LoopInterface::class);
121
122
        if ($startup) {
123
            $this->info('Fetching last messages...');
124
            $this->onMessageFallback($loop, $gitter, 1);
125
126
            return $this;
127
        }
128
129
        $this->info(sprintf(
130
            'Startup gitter listener for %s at [%s]',
131
            $room->url,
132
            Carbon::now()->toDateTimeString()
133
        ));
134
135
        $gitter->onMessage(function (GitterMessage $msg) {
136
            app(Client::class)->setFallbackMode(false);
137
            $this->onMessage($msg);
138
139
        }, function (\Throwable $e) use ($loop, $gitter) {
0 ignored issues
show
Unused Code introduced by
The parameter $e 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...
140
            $this->warn('Stream not available. Use message fallback fetch mode.');
141
142
            app(Client::class)->setFallbackMode(true);
143
            $this->onMessageFallback($loop, $gitter);
144
        });
145
146
        return $this;
147
    }
148
149
    /**
150
     * @param LoopInterface $loop
151
     * @param GitterRoom $gitter
152
     * @param int $timeout
153
     */
154
    protected function onMessageFallback(LoopInterface $loop, GitterRoom $gitter, $timeout = 10)
155
    {
156
        /** @var Message $lastMessage */
157
        $lastMessage = Message::where('room_id', $gitter->id)
158
            ->latest('created_at')
159
            ->first();
160
161
        if ($lastMessage) {
162
            $loop->addTimer($timeout, function () use ($gitter, $lastMessage) {
0 ignored issues
show
Documentation introduced by
$timeout is of type integer, but the function expects a object<React\EventLoop\numeric>.

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...
163
                $gitter
164
                    ->getMessages($lastMessage->gitter_id, GitterRoom::MESSAGE_FETCH_ASC)
165
                    ->fetch(function (GitterMessage $message, Controls $controls) {
166
                        $this->onMessage($message);
167
                        $controls->next();
168
                    })
169
                    ->then(function () use ($gitter) {
170
                        $this->warn('Connection...');
171
                        $this->listen($gitter);
172
                    }, function(\Throwable $e) {
173
                        $this->error($e->getMessage());
174
                    });
175
            });
176
        } else {
177
            $this->listen($gitter);
178
        }
179
    }
180
181
    /**
182
     * @param GitterMessage $gitter
183
     */
184
    protected function onMessage(GitterMessage $gitter)
185
    {
186
        $message = Message::make($gitter);
187
188
        if ($message->gitter_id === \Auth::user()->gitter_id) {
189
            return;
190
        }
191
192
        try {
193
            /** @var MiddlewareBuilder $builder */
194
            $builder = app(MiddlewareBuilder::class);
195
            $builder->fire($gitter->room, $message);
196
197
        } catch (\Throwable $e) {
198
            $this->error($e->getMessage());
199
        }
200
    }
201
}
202
203
204
205
206
207