Completed
Push — master ( 10426d...42f289 )
by Dan
01:36
created

Yabot::onMessage()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 9.0856
c 0
b 0
f 0
cc 3
eloc 15
nc 4
nop 1
1
<?php
2
3
namespace Nopolabs\Yabot;
4
5
use DateTime;
6
use Exception;
7
use Nopolabs\Yabot\Helpers\ConfigTrait;
8
use Nopolabs\Yabot\Helpers\LogTrait;
9
use Nopolabs\Yabot\Helpers\LoopTrait;
10
use Nopolabs\Yabot\Helpers\SlackTrait;
11
use Nopolabs\Yabot\Message\MessageFactory;
12
use Nopolabs\Yabot\Plugin\PluginInterface;
13
use Nopolabs\Yabot\Plugin\PluginManager;
14
use Nopolabs\Yabot\Slack\Client;
15
use Psr\Log\LoggerInterface;
16
use React\EventLoop\LoopInterface;
17
use React\EventLoop\Timer\TimerInterface;
18
use React\Promise\Timer;
19
use Slack\Payload;
20
use Slack\User;
21
use Throwable;
22
23
class Yabot
24
{
25
    use LogTrait;
26
    use LoopTrait;
27
    use SlackTrait;
28
    use ConfigTrait;
29
30
    /** @var MessageFactory */
31
    private $messageFactory;
32
33
    /** @var PluginManager */
34
    private $pluginManager;
35
36
    /** @var string */
37
    private $messageLog;
38
39
    /** @var TimerInterface */
40
    private $monitor;
41
42
    /** @var bool */
43
    private $pong;
44
45
    public function __construct(
46
        LoggerInterface $logger,
47
        LoopInterface $eventLoop,
48
        Client $slackClient,
49
        MessageFactory $messageFactory,
50
        PluginManager $pluginManager,
51
        array $config = []
52
    ) {
53
        $this->setLog($logger);
54
        $this->setLoop($eventLoop);
55
        $this->setSlack($slackClient);
56
        $this->setConfig($config);
57
        $this->messageFactory = $messageFactory;
58
        $this->pluginManager = $pluginManager;
59
        $this->messageLog = null;
60
    }
61
62
    public function getMessageLog()
63
    {
64
        return $this->messageLog;
65
    }
66
67
    public function setMessageLog(string $messageLog = null)
68
    {
69
        $this->messageLog = $messageLog ?? null;
70
    }
71
72
    public function init(array $plugins)
73
    {
74
        foreach ($plugins as $pluginId => $plugin) {
75
            /** @var PluginInterface $plugin */
76
77
            $this->info("loading $pluginId");
78
79
            try {
80
                $this->pluginManager->loadPlugin($pluginId, $plugin);
81
            } catch (Exception $e) {
82
                $this->warning("Unhandled Exception while loading $pluginId: ".$e->getMessage());
83
                $this->warning($e->getTraceAsString());
84
            }
85
        }
86
    }
87
88
    public function run()
89
    {
90
        $slack = $this->getSlack();
91
92
        $slack->init();
93
94
        $this->getLog()->info('Connecting...');
95
96
        Timer\timeout($slack->connect(), 30, $this->getLoop())
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface React\Promise\PromiseInterface as the method otherwise() does only exist in the following implementations of said interface: React\Promise\FulfilledPromise, React\Promise\LazyPromise, React\Promise\Promise, React\Promise\RejectedPromise.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
97
            ->then(function () {
98
                $this->getLog()->info('Connected.');
99
                $this->connected();
100
            })
101
            ->otherwise(function (Timer\TimeoutException $error) {
102
                $this->getLog()->error($error->getMessage());
103
                $this->getLog()->error('Connection failed, shutting down.');
104
                $this->shutDown();
105
            })
106
            ->otherwise(function ($error) {
0 ignored issues
show
Unused Code introduced by
The parameter $error 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...
107
                $this->getLog()->error('Connection failed, shutting down.');
108
                $this->shutDown();
109
            });
110
111
        $this->addMemoryReporting();
112
113
        $this->getLoop()->run();
114
    }
115
116
    public function shutDown()
117
    {
118
        $this->getLog()->error('Shutting down...');
119
120
        $this->getSlack()->disconnect();
121
        $this->getLoop()->stop();
122
    }
123
124
    public function reconnect()
125
    {
126
        $this->getLog()->error('Reconnecting...');
127
128
        if ($this->monitor) {
129
            $this->loop->cancelTimer($this->monitor);
130
        }
131
132
        $this->getSlack()->reconnect()->then(
133
            function () {
134
                $this->getLog()->info('Reconnected');
135
                $this->monitor = $this->startConnectionMonitor();
136
            },
137
            function () {
138
                $this->getLog()->error('Reconnect failed, shutting down.');
139
                $this->shutDown();
140
            }
141
        );
142
    }
143
144
    public function connected()
145
    {
146
        $slack = $this->getSlack();
147
148
        $slack->update(function(User $authedUser) {
149
            $this->pluginManager->setAuthedUser($authedUser);
150
        });
151
152
        $slack->onEvent('message', [$this, 'onMessage']);
153
        $slack->onEvent('team_join', [$this, 'onTeamJoin']);
154
155
        $this->monitor = $this->startConnectionMonitor();
156
    }
157
158
    public function onMessage(Payload $payload)
159
    {
160
        $data = $payload->getData();
161
162
        $this->debug('Received message', $data);
163
164
        try {
165
            $this->logMessage($data);
166
            $message = $this->messageFactory->create($data);
167
        } catch (Throwable $throwable) {
168
            $errmsg = $throwable->getMessage()."\n"
169
                .$throwable->getTraceAsString()."\n"
170
                ."Payload data: ".json_encode($data);
171
            $this->warning($errmsg);
172
            return;
173
        }
174
175
        if ($message->isSelf()) {
176
            return;
177
        }
178
179
        $this->pluginManager->dispatchMessage($message);
180
    }
181
182
    public function onTeamJoin(Payload $payload)
0 ignored issues
show
Unused Code introduced by
The parameter $payload 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...
183
    {
184
        $this->getSlack()->updateUsers();
185
    }
186
187
    public function getHelp() : string
188
    {
189
        return implode("\n", $this->pluginManager->getHelp());
190
    }
191
192
    public function getStatus() : string
193
    {
194
        $statuses = $this->pluginManager->getStatuses();
195
196
        array_unshift($statuses, $this->getFormattedMemoryUsage());
197
198
        return implode("\n", $statuses);
199
    }
200
201
    protected function addMemoryReporting()
202
    {
203
        $now = new DateTime();
204
        $then = new DateTime('+1 hour');
205
        $then->setTime($then->format('H'), 0, 0);
206
        $delay = $then->getTimestamp() - $now->getTimestamp();
207
208
        $this->addTimer($delay, function() {
209
            $this->info($this->getFormattedMemoryUsage());
210
            $this->addPeriodicTimer(3600, function() {
211
                $this->info($this->getFormattedMemoryUsage());
212
            });
213
        });
214
    }
215
216
    protected function getFormattedMemoryUsage() : string
217
    {
218
        $memory = memory_get_usage() / 1024;
219
        $formatted = number_format($memory, 3).'K';
220
        return "Current memory usage: {$formatted}";
221
    }
222
223
    protected function logMessage($data)
224
    {
225
        if ($this->messageLog !== null) {
226
            file_put_contents($this->messageLog, json_encode($data) . "\n", FILE_APPEND);
227
        }
228
    }
229
230
    /**
231
     * @return TimerInterface|null
232
     */
233
    protected function startConnectionMonitor()
234
    {
235
        if ($interval = $this->get('connection_monitor.interval')) {
236
237
            $this->getLog()->info("Monitoring websocket connection every $interval seconds.");
238
            $this->notify("Monitoring websocket connection every $interval seconds.");
239
240
            $this->ping();
241
242
            return $this->loop->addPeriodicTimer($interval, function () {
243
                $this->checkPong();
244
                $this->ping();
245
            });
246
        }
247
    }
248
249
    protected function checkPong()
250
    {
251
        if (!$this->pong) {
252
            $this->getLog()->error('No pong.');
253
254
            $failureStrategy = $this->get('connection_monitor.failure_strategy', 'reconnect');
255
256
            if ($failureStrategy === 'reconnect') {
257
                $this->reconnect();
258
                return;
259
            }
260
261
            if ($failureStrategy !== 'shutdown') {
262
                $this->getLog()->error("Unknown connection_monitor.failure_strategy '$failureStrategy'");
263
            }
264
265
            $this->shutDown();
266
        }
267
    }
268
269
    protected function ping()
270
    {
271
        $this->pong = false;
272
273
        $this->getSlack()->ping()
274
            ->then(
275
                function (Payload $payload) {
276
                    $this->getLog()->info($payload->toJson());
277
                    $this->pong = true;
278
                }
279
            );
280
    }
281
282
    protected function notify(string $message)
283
    {
284
        if ($user = $this->get('notify.user')) {
285
            $this->getSlack()->directMessage($message, $user);
286
        }
287
    }
288
}
289