Passed
Push — master ( 75cc50...5712f6 )
by Ehsan
02:31
created

Slackbot::getCommandObjectByMessage()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4.128

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 8
cts 10
cp 0.8
rs 8.9197
c 0
b 0
f 0
cc 4
eloc 11
nc 5
nop 1
crap 4.128
1
<?php
2
3
namespace Botonomous;
4
5
use Botonomous\listener\EventListener;
6
use Botonomous\plugin\AbstractPlugin;
7
8
/**
9
 * Class Botonomous.
10
 */
11
class Slackbot extends AbstractBot
12
{
13
    private $commands;
14
    private $lastError;
15
    private $currentCommand;
16
17
    /**
18
     * Botonomous constructor.
19
     *
20
     * @param Config|null $config
21
     *
22
     * @throws \Exception
23
     */
24 42
    public function __construct(Config $config = null)
25
    {
26 42
        if ($config !== null) {
27 6
            $this->setConfig($config);
28
        }
29
30 42
        $this->setTimezone();
31 42
    }
32
33
    /**
34
     * Set the timezone.
35
     */
36 42
    private function setTimezone()
37
    {
38
        // set timezone
39 42
        date_default_timezone_set($this->getConfig()->get('timezone'));
40 42
    }
41
42
    /**
43
     * @param null|string $key
44
     *
45
     * @return mixed
46
     */
47 10
    public function getRequest($key = null)
48
    {
49 10
        return $this->getListener()->getRequest($key);
50
    }
51
52
    /**
53
     * @return AbstractBaseSlack|null|void
54
     */
55 1
    private function handleMessageActions()
56
    {
57 1
        $post = $this->getRequestUtility()->getPost();
58
59
        // ignore if payload is not set
60 1
        if (!isset($post['payload'])) {
61
            /* @noinspection PhpInconsistentReturnPointsInspection */
62 1
            return;
63
        }
64
65
        // posted payload is in JSON
66 1
        $payload = json_decode($post['payload'], true);
67
68 1
        return (new MessageAction())->load($payload);
69
    }
70
71
    /**
72
     * @throws \Exception
73
     */
74 5
    private function handleSendResponse()
75
    {
76
        // 1. Start listening
77 5
        $this->getListener()->listen();
78
79
        // 2. verify the request
80
        try {
81 5
            $verificationResult = $this->getListener()->verifyRequest();
82
83 5
            if ($verificationResult['success'] !== true) {
84 5
                throw new \Exception($verificationResult['message']);
85
            }
86 2
        } catch (\Exception $e) {
87 2
            throw $e;
88
        }
89
90
        // 3. pre process the request
91 3
        $this->preProcessRequest();
92
93
        // 4. check access control
94 3
        if ($this->checkAccessControl() !== true) {
95 2
            return;
96
        }
97
98
        // 5. set the current command
99 1
        $message = $this->getListener()->getMessage();
100 1
        $this->setCurrentCommand($this->getMessageUtility()->extractCommandName($message));
101
102
        // 6. log the message
103 1
        $this->getLoggerUtility()->logChat(__METHOD__, $message);
104
105
        // 7. send confirmation message if is enabled
106 1
        $this->getSender()->sendConfirmation();
107
108
        // 8. And send the response to the channel, only if the response is not empty
109 1
        $response = $this->respond($message);
110
111 1
        if (!empty($response)) {
112 1
            $this->getSender()->send($response);
113
        }
114 1
    }
115
116
    /**
117
     * @return bool
118
     */
119 3
    private function checkAccessControl()
120
    {
121
        // if accessControlEnabled is not set true ignore the check and return true
122 3
        if ($this->getConfig()->get('accessControlEnabled') !== true) {
123 1
            return true;
124
        }
125
126 2
        if ($this->getBlackList()->isBlackListed() !== false) {
127
            // found in blacklist
128 1
            $this->getSender()->send($this->getDictionary()->get('generic-messages')['blacklistedMessage']);
129
130 1
            return false;
131
        }
132
133 1
        if ($this->getWhiteList()->isWhiteListed() !== true) {
134
            // not found in whitelist
135 1
            $this->getSender()->send($this->getDictionary()->get('generic-messages')['whitelistedMessage']);
136
137 1
            return false;
138
        }
139
140
        return true;
141
    }
142
143
    /**
144
     * @throws \Exception
145
     */
146 8
    public function run()
147
    {
148 8
        switch ($this->getListener()->determineAction()) {
149 8
            case 'oauth':
150 1
                return $this->handleOAuth();
151 7
            case 'message_actions':
152 1
                return $this->handleMessageActions();
153 6
            case 'url_verification':
154 1
                return $this->handleUrlVerification();
155
            default:
156 5
                return $this->handleSendResponse();
157
        }
158
    }
159
160
    /**
161
     * handle OAuth.
162
     */
163 1
    private function handleOAuth()
164
    {
165 1
        return $this->getOauth()->doOauth();
166
    }
167
168
    /**
169
     * @throws \Exception
170
     */
171 1
    private function handleUrlVerification()
172
    {
173 1
        $request = $this->getRequestUtility()->getPostedBody();
174
175 1
        if (empty($request['challenge'])) {
176
            throw new \Exception('Challenge is missing for URL verification');
177
        }
178
179 1
        echo $request['challenge'];
180 1
    }
181
182
    /**
183
     * Pre-process the request.
184
     */
185 3
    private function preProcessRequest()
186
    {
187 3
        $request = $this->getListener()->getRequest();
188
189
        // remove the trigger_word from beginning of the message
190 3
        if (!empty($request['trigger_word'])) {
191 3
            $request['text'] = $this->getMessageUtility()->removeTriggerWord(
192 3
                $request['text'],
193 3
                $request['trigger_word']
194
            );
195
196 3
            $this->getListener()->setRequest($request);
197
        }
198 3
    }
199
200
    /**
201
     * @param null $message
202
     *
203
     * @throws \Exception
204
     *
205
     * @return mixed
206
     */
207 4
    public function respond($message = null)
208
    {
209
        try {
210 4
            $command = $this->getCommandByMessage($message);
211
212 4
            if (!$command instanceof Command) {
213
                // something went wrong, error will tell us!
214 2
                return $this->getLastError();
215
            }
216
217 3
            $pluginClass = $this->getPluginClassByCommand($command);
218
219
            // check action exists
220 3
            $action = $command->getAction();
221 3
            if (!method_exists($pluginClass, $action)) {
222 1
                $className = get_class($pluginClass);
223 1
                throw new \Exception("Action / function: '{$action}' does not exist in '{$className}'");
224
            }
225
226 2
            return $pluginClass->$action();
227 1
        } catch (\Exception $e) {
228 1
            throw $e;
229
        }
230
    }
231
232
    /**
233
     * Get plugin class by command.
234
     *
235
     * @param Command $command
236
     *
237
     * @throws \Exception
238
     *
239
     * @return AbstractPlugin
240
     */
241 3
    private function getPluginClassByCommand(Command $command)
242
    {
243
        // create the class
244 3
        $pluginClassFile = $command->getClass();
245 3
        $pluginClass = new $pluginClassFile($this);
246
247
        // check class is valid
248 3
        if (!$pluginClass instanceof AbstractPlugin) {
249
            $className = get_class($pluginClass);
250
            throw new \Exception("Couldn't create class: '{$className}'");
251
        }
252
253 3
        return $pluginClass;
254
    }
255
256
    /**
257
     * @param null $message
258
     *
259
     * @throws \Exception
260
     *
261
     * @return bool|Command|void
262
     */
263 7
    public function getCommandByMessage($message = null)
264
    {
265
        // If message is not set, get it from the current request
266 7
        if ($message === null) {
267 4
            $message = $this->getListener()->getMessage();
268
        }
269
270 7
        if (empty($message)) {
271 1
            $this->setLastError('Message is empty');
272
273 1
            return false;
274
        }
275
276
        /*
277
         * Process the message.
278
         */
279
        try {
280 6
            return $this->getCommandObjectByMessage($message);
281
        } catch (\Exception $e) {
282
            throw $e;
283
        }
284
    }
285
286
    /**
287
     * @param $message
288
     *
289
     * @throws \Exception
290
     *
291
     * @return bool|Command|void
292
     */
293 6
    private function getCommandObjectByMessage($message)
294
    {
295 6
        $command = $this->getMessageUtility()->extractCommandName($message);
296
297
        // check command name
298 6
        if (empty($command)) {
299
            // get the default command if no command is find in the message
300 2
            $command = $this->getConfig()->get('defaultCommand');
301
302 2
            if (empty($command)) {
303 2
                $this->setLastError($this->getDictionary()->get('generic-messages')['noCommandMessage']);
304
305 2
                return false;
306
            }
307
        }
308
309
        try {
310 4
            return $this->getCommandObjectByCommand($command);
311
        } catch (\Exception $e) {
312
            throw $e;
313
        }
314
    }
315
316
    /**
317
     * @param $command
318
     *
319
     * @throws \Exception
320
     *
321
     * @return bool|Command|void
322
     */
323 4
    private function getCommandObjectByCommand($command)
324
    {
325
        try {
326 4
            $commandObject = $this->getCommandContainer()->getAsObject($command);
327
328 4
            if ($this->validateCommandObject($commandObject) !== true) {
329 1
                return false;
330
            }
331
332 4
            return $commandObject;
333
        } catch (\Exception $e) {
334
            throw $e;
335
        }
336
    }
337
338
    /**
339
     * Validate the command object.
340
     *
341
     * @param Command|null $commandObject
342
     *
343
     * @throws \Exception
344
     *
345
     * @return bool
346
     */
347 4
    private function validateCommandObject($commandObject)
348
    {
349
        // check command details
350 4
        if (empty($commandObject)) {
351 1
            $this->setLastError(
352 1
                $this->getDictionary()->getValueByKey('generic-messages', 'unknownCommandMessage')
353
            );
354
355 1
            return false;
356
        }
357
358
        // check the plugin for the command
359 4
        if (empty($commandObject->getPlugin())) {
360
            throw new \Exception('Plugin is not set for this command');
361
        }
362
363 4
        return true;
364
    }
365
366
    /**
367
     * @return array
368
     */
369 2
    public function getCommands()
370
    {
371 2
        if (!isset($this->commands)) {
372 1
            $this->setCommands($this->getCommandContainer()->getAllAsObject());
373
        }
374
375 2
        return $this->commands;
376
    }
377
378
    /**
379
     * @param array $commands
380
     */
381 2
    public function setCommands(array $commands)
382
    {
383 2
        $this->commands = $commands;
384 2
    }
385
386
    /**
387
     * @return string
388
     */
389 4
    public function getLastError()
390
    {
391 4
        return $this->lastError;
392
    }
393
394
    /**
395
     * @param string $lastError
396
     */
397 4
    public function setLastError($lastError)
398
    {
399 4
        $this->lastError = $lastError;
400 4
    }
401
402
    /**
403
     * Return the current command.
404
     *
405
     * @return string
406
     */
407 1
    public function getCurrentCommand()
408
    {
409 1
        return $this->currentCommand;
410
    }
411
412
    /**
413
     * @param string $currentCommand
414
     */
415 2
    public function setCurrentCommand($currentCommand)
416
    {
417 2
        $this->currentCommand = $currentCommand;
418 2
    }
419
420
    /**
421
     * Determine if bot user id is mentioned in the message.
422
     *
423
     * @return bool
424
     */
425 1
    public function youTalkingToMe()
426
    {
427 1
        $message = $this->getListener()->getMessage();
428
429 1
        if (empty($message)) {
430 1
            return false;
431
        }
432
433 1
        if ($this->getMessageUtility()->isBotMentioned($message) === true) {
434 1
            return true;
435
        }
436
437 1
        $listener = $this->getListener();
438
        // check direct messages
439 1
        return $listener instanceof EventListener && $listener->getEvent()->isDirectMessage() === true;
440
    }
441
}
442