Passed
Push — master ( 4904f7...9a2e0d )
by Ehsan
02:54
created

Slackbot::setLastError()   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
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 35
    public function __construct(Config $config = null)
25
    {
26 35
        if ($config !== null) {
27 4
            $this->setConfig($config);
28
        }
29
30
        // set timezone
31 35
        date_default_timezone_set($this->getConfig()->get('timezone'));
32 35
    }
33
34
    /**
35
     * @param null|string $key
36
     *
37
     * @return mixed
38
     */
39 8
    public function getRequest($key = null)
40
    {
41 8
        return $this->getListener()->getRequest($key);
42
    }
43
44
    /**
45
     * @return string|null
46
     */
47 7
    private function determineAction()
48
    {
49 7
        $utility = $this->getRequestUtility();
50 7
        $getRequest = $utility->getGet();
51
52 7
        if (!empty($getRequest['action'])) {
53 2
            return strtolower($getRequest['action']);
54
        }
55
56 5
        $request = $utility->getPostedBody();
57
58 5
        if (isset($request['type']) && $request['type'] === 'url_verification') {
59 1
            return 'url_verification';
60
        }
61 4
    }
62
63
    /**
64
     * @return null|AbstractBaseSlack
65
     */
66 1
    private function handleMessageActions()
67
    {
68 1
        $post = $this->getRequestUtility()->getPost();
69
70
        // ignore if payload is not set
71 1
        if (!isset($post['payload'])) {
72
            /* @noinspection PhpInconsistentReturnPointsInspection */
73 1
            return;
74
        }
75
76
        // posted payload is in JSON
77 1
        $payload = json_decode($post['payload'], true);
78
79 1
        return (new MessageAction())->load($payload);
80
    }
81
82
    /**
83
     * @throws \Exception
84
     */
85 4
    private function handleSendResponse()
86
    {
87
        // 1. Start listening
88 4
        $this->getListener()->listen();
89
90
        // 2. verify the request
91
        try {
92 4
            $verificationResult = $this->verifyRequest();
93
94 4
            if ($verificationResult['success'] !== true) {
95 4
                throw new \Exception($verificationResult['message']);
96
            }
97 1
        } catch (\Exception $e) {
98 1
            throw $e;
99
        }
100
101
        // 3. pre process the request
102 3
        $this->preProcessRequest();
103
104
        // 4. check access control
105 3
        if ($this->checkAccessControl() !== true) {
106 2
            return;
107
        }
108
109
        // 5. set the current command
110 1
        $message = $this->getMessage();
111 1
        $this->setCurrentCommand($this->getMessageUtility()->extractCommandName($message));
112
113
        // 6. log the message
114 1
        if (empty($this->getRequest('debug'))) {
115 1
            $this->getLoggerUtility()->logRaw($this->getFormattingUtility()->newLine());
116 1
            $this->getLoggerUtility()->logChat(__METHOD__, $message);
117
        }
118
119
        // 7. send confirmation message if is enabled
120 1
        $this->sendConfirmation();
121
122
        // 8. And send the response to the channel, only if the response is not empty
123 1
        $response = $this->respond($message);
124
125 1
        if (!empty($response)) {
126 1
            $this->getSender()->send($response);
127
        }
128 1
    }
129
130
    /**
131
     * @return bool
132
     */
133 3
    private function checkAccessControl()
134
    {
135
        // if accessControlEnabled is not set true ignore the check and return true
136 3
        if ($this->getConfig()->get('accessControlEnabled') !== true) {
137 1
            return true;
138
        }
139
140 2
        if ($this->getBlackList()->isBlackListed() !== false) {
141
            // found in blacklist
142 1
            $this->getSender()->send($this->getConfig()->get('blacklistedMessage'));
143
144 1
            return false;
145
        }
146
147 1
        if ($this->getWhiteList()->isWhiteListed() !== true) {
148
            // not found in whitelist
149 1
            $this->getSender()->send($this->getConfig()->get('whitelistedMessage'));
150
151 1
            return false;
152
        }
153
154
        return true;
155
    }
156
157
    /**
158
     * @throws \Exception
159
     */
160 7
    public function run()
161
    {
162 7
        switch ($this->determineAction()) {
163 7
            case 'oauth':
164 1
                return $this->handleOAuth();
165 6
            case 'message_actions':
166 1
                return $this->handleMessageActions();
167 5
            case 'url_verification':
168 1
                return $this->handleUrlVerification();
169
            default:
170 4
                return $this->handleSendResponse();
171
        }
172
    }
173
174
    /**
175
     * handle OAuth.
176
     */
177 1
    private function handleOAuth()
178
    {
179 1
        return $this->getOauth()->doOauth();
180
    }
181
182
    /**
183
     * @throws \Exception
184
     *
185
     * @return mixed
186
     */
187 1
    private function handleUrlVerification()
188
    {
189 1
        $request = $this->getRequestUtility()->getPostedBody();
190
191 1
        if (empty($request['challenge'])) {
192
            throw new \Exception('Challenge is missing for URL verification');
193
        }
194
195 1
        echo $request['challenge'];
196 1
    }
197
198
    /**
199
     * Send confirmation.
200
     */
201 1
    private function sendConfirmation()
202
    {
203 1
        $userId = $this->getRequest('user_id');
204
205 1
        $user = '';
206 1
        if (!empty($userId)) {
207 1
            $user = $this->getMessageUtility()->linkToUser($userId).' ';
208
        }
209
210 1
        $confirmMessage = $this->getConfig()->get('confirmReceivedMessage', ['user' => $user]);
211
212 1
        if (!empty($confirmMessage)) {
213 1
            $this->getSender()->send($confirmMessage);
214
        }
215 1
    }
216
217
    /**
218
     * Pre-process the request.
219
     */
220 3
    private function preProcessRequest()
221
    {
222 3
        $request = $this->getListener()->getRequest();
223
224
        // remove the trigger_word from beginning of the message
225 3
        if (!empty($request['trigger_word'])) {
226 3
            $request['text'] = $this->getMessageUtility()->removeTriggerWord(
227 3
                $request['text'],
228 3
                $request['trigger_word']
229
            );
230
231 3
            $this->getListener()->setRequest($request);
232
        }
233 3
    }
234
235
    /**
236
     * @param null $message
237
     *
238
     * @throws \Exception
239
     *
240
     * @return mixed
241
     */
242 4
    public function respond($message = null)
243
    {
244
        try {
245 4
            $command = $this->getCommandByMessage($message);
246
247 4
            if (!$command instanceof Command) {
248
                // something went wrong, error will tell us!
249 2
                return $this->getLastError();
250
            }
251
252
            // create the class
253 3
            $pluginClassFile = $command->getClass();
254 3
            $pluginClass = new $pluginClassFile($this);
255
256
            // check class is valid
257 3
            if (!$pluginClass instanceof AbstractPlugin) {
258
                throw new \Exception("Couldn't create class: '{$pluginClassFile}'");
259
            }
260
261
            // check action exists
262 3
            $action = $command->getAction();
263 3
            if (!method_exists($pluginClass, $action)) {
264 1
                throw new \Exception("Action / function: '{$action}' does not exist in '{$pluginClassFile}'");
265
            }
266
267 2
            return $pluginClass->$action();
268 1
        } catch (\Exception $e) {
269 1
            throw $e;
270
        }
271
    }
272
273
    /**
274
     * @param null $message
275
     *
276
     * @throws \Exception
277
     *
278
     * @return bool|Command
279
     */
280 7
    public function getCommandByMessage($message = null)
281
    {
282
        // If message is not set, get it from the current request
283 7
        if ($message === null) {
284 4
            $message = $this->getMessage();
285
        }
286
287 7
        if (empty($message)) {
288 1
            $this->setLastError('Message is empty');
289
290 1
            return false;
291
        }
292
293
        /**
294
         * Process the message.
295
         */
296 6
        $command = $this->getMessageUtility()->extractCommandName($message);
297
298 6
        $config = $this->getConfig();
299
300
        // check command name
301 6
        if (empty($command)) {
302
            // get the default command if no command is find in the message
303 2
            $command = $config->get('defaultCommand');
304
305 2
            if (empty($command)) {
306 2
                $this->setLastError($config->get('noCommandMessage'));
307
308 2
                return false;
309
            }
310
        }
311
312 4
        $commandObject = $this->getCommandContainer()->getAsObject($command);
313
314
        // check command details
315 4
        if (empty($commandObject)) {
316 1
            $this->setLastError($config->get('unknownCommandMessage', ['command' => $command]));
317
318 1
            return false;
319
        }
320
321 4
        if (!$commandObject instanceof Command) {
322
            throw new \Exception('Command is not an object');
323
        }
324
325
        // check the plugin for the command
326 4
        if (empty($commandObject->getPlugin())) {
327
            throw new \Exception('Plugin is not set for this command');
328
        }
329
330 4
        return $commandObject;
331
    }
332
333
    /**
334
     * @throws \Exception
335
     *
336
     * @return array<string,boolean|string>
337
     */
338 4
    private function verifyRequest()
339
    {
340 4
        $originCheck = $this->getListener()->verifyOrigin();
341
342 4
        if (!isset($originCheck['success'])) {
343
            throw new \Exception('Success must be provided in verifyOrigin response');
344
        }
345
346 4
        if ($originCheck['success'] !== true) {
347
            return [
348
                'success' => false,
349
                'message' => $originCheck['message'],
350
            ];
351
        }
352
353 4
        if ($this->getListener()->isThisBot() !== false) {
354
            return [
355 1
                'success' => false,
356
                'message' => 'Request comes from the bot',
357
            ];
358
        }
359
360
        return [
361 3
            'success' => true,
362
            'message' => 'Yay!',
363
        ];
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 string
404
     */
405 1
    public function getCurrentCommand()
406
    {
407 1
        return $this->currentCommand;
408
    }
409
410
    /**
411
     * @param string $currentCommand
412
     */
413 2
    public function setCurrentCommand($currentCommand)
414
    {
415 2
        $this->currentCommand = $currentCommand;
416 2
    }
417
418
    /**
419
     * Return message based on the listener
420
     * If listener is event and event text is empty, fall back to request text.
421
     *
422
     * @return mixed|string
423
     */
424 11
    public function getMessage()
425
    {
426 11
        $listener = $this->getListener();
427 11
        if ($listener instanceof EventListener && $listener->getEvent() instanceof Event) {
428 1
            $message = $listener->getEvent()->getText();
429
430 1
            if (!empty($message)) {
431 1
                return $message;
432
            }
433
        }
434
435 10
        return $listener->getRequest('text');
436
    }
437
438
    /**
439
     * Determine if bot user id is mentioned in the message.
440
     *
441
     * @return bool
442
     */
443 1
    public function youTalkingToMe()
444
    {
445 1
        $message = $this->getMessage();
446
447 1
        if (empty($message)) {
448 1
            return false;
449
        }
450
451 1
        return $this->getMessageUtility()->isBotMentioned($message);
452
    }
453
}
454