Completed
Pull Request — master (#173)
by Ehsan
03:35
created

Slackbot::handleSendResponse()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 41
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 41
ccs 18
cts 18
cp 1
rs 8.439
c 0
b 0
f 0
cc 5
eloc 18
nc 6
nop 0
crap 5
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 null|AbstractBaseSlack
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
     * @return mixed
172
     */
173 1
    private function handleUrlVerification()
174
    {
175 1
        $request = $this->getRequestUtility()->getPostedBody();
176
177 1
        if (empty($request['challenge'])) {
178
            throw new \Exception('Challenge is missing for URL verification');
179
        }
180
181 1
        echo $request['challenge'];
182 1
    }
183
184
    /**
185
     * Pre-process the request.
186
     */
187 3
    private function preProcessRequest()
188
    {
189 3
        $request = $this->getListener()->getRequest();
190
191
        // remove the trigger_word from beginning of the message
192 3
        if (!empty($request['trigger_word'])) {
193 3
            $request['text'] = $this->getMessageUtility()->removeTriggerWord(
194 3
                $request['text'],
195 3
                $request['trigger_word']
196
            );
197
198 3
            $this->getListener()->setRequest($request);
199
        }
200 3
    }
201
202
    /**
203
     * @param null $message
204
     *
205
     * @throws \Exception
206
     *
207
     * @return mixed
208
     */
209 4
    public function respond($message = null)
210
    {
211
        try {
212 4
            $command = $this->getCommandByMessage($message);
213
214 4
            if (!$command instanceof Command) {
215
                // something went wrong, error will tell us!
216 2
                return $this->getLastError();
217
            }
218
219
            // create the class
220 3
            $pluginClassFile = $command->getClass();
221 3
            $pluginClass = new $pluginClassFile($this);
222
223
            // check class is valid
224 3
            if (!$pluginClass instanceof AbstractPlugin) {
225
                throw new \Exception("Couldn't create class: '{$pluginClassFile}'");
226
            }
227
228
            // check action exists
229 3
            $action = $command->getAction();
230 3
            if (!method_exists($pluginClass, $action)) {
231 1
                throw new \Exception("Action / function: '{$action}' does not exist in '{$pluginClassFile}'");
232
            }
233
234 2
            return $pluginClass->$action();
235 1
        } catch (\Exception $e) {
236 1
            throw $e;
237
        }
238
    }
239
240
    /**
241
     * @param null $message
242
     *
243
     * @throws \Exception
244
     *
245
     * @return bool|Command
246
     */
247 7
    public function getCommandByMessage($message = null)
248
    {
249
        // If message is not set, get it from the current request
250 7
        if ($message === null) {
251 4
            $message = $this->getListener()->getMessage();
252
        }
253
254 7
        if (empty($message)) {
255 1
            $this->setLastError('Message is empty');
256
257 1
            return false;
258
        }
259
260
        /**
261
         * Process the message.
262
         */
263 6
        $command = $this->getMessageUtility()->extractCommandName($message);
264
265 6
        $config = $this->getConfig();
266
267
        // check command name
268 6
        if (empty($command)) {
269
            // get the default command if no command is find in the message
270 2
            $command = $config->get('defaultCommand');
271
272 2
            if (empty($command)) {
273 2
                $this->setLastError($this->getDictionary()->get('generic-messages')['noCommandMessage']);
274
275 2
                return false;
276
            }
277
        }
278
279 4
        $commandObject = $this->getCommandContainer()->getAsObject($command);
280
281
        // check command details
282 4
        if (empty($commandObject)) {
283 1
            $this->setLastError(
284 1
                $this->getDictionary()->getValueByKey(
285 1
                    'generic-messages',
286 1
                    'unknownCommandMessage',
287 1
                    ['command' => $command]
288
                )
289
            );
290
291 1
            return false;
292
        }
293
294 4
        if (!$commandObject instanceof Command) {
295
            throw new \Exception('Command is not an object');
296
        }
297
298
        // check the plugin for the command
299 4
        if (empty($commandObject->getPlugin())) {
300
            throw new \Exception('Plugin is not set for this command');
301
        }
302
303 4
        return $commandObject;
304
    }
305
306
    /**
307
     * @return array
308
     */
309 2
    public function getCommands()
310
    {
311 2
        if (!isset($this->commands)) {
312 1
            $this->setCommands($this->getCommandContainer()->getAllAsObject());
313
        }
314
315 2
        return $this->commands;
316
    }
317
318
    /**
319
     * @param array $commands
320
     */
321 2
    public function setCommands(array $commands)
322
    {
323 2
        $this->commands = $commands;
324 2
    }
325
326
    /**
327
     * @return string
328
     */
329 4
    public function getLastError()
330
    {
331 4
        return $this->lastError;
332
    }
333
334
    /**
335
     * @param string $lastError
336
     */
337 4
    public function setLastError($lastError)
338
    {
339 4
        $this->lastError = $lastError;
340 4
    }
341
342
    /**
343
     * Return the current command.
344
     *
345
     * @return string
346
     */
347 1
    public function getCurrentCommand()
348
    {
349 1
        return $this->currentCommand;
350
    }
351
352
    /**
353
     * @param string $currentCommand
354
     */
355 2
    public function setCurrentCommand($currentCommand)
356
    {
357 2
        $this->currentCommand = $currentCommand;
358 2
    }
359
360
    /**
361
     * Determine if bot user id is mentioned in the message.
362
     *
363
     * @return bool
364
     */
365 1
    public function youTalkingToMe()
366
    {
367 1
        $message = $this->getListener()->getMessage();
368
369 1
        if (empty($message)) {
370 1
            return false;
371
        }
372
373 1
        if ($this->getMessageUtility()->isBotMentioned($message) === true) {
374 1
            return true;
375
        }
376
377 1
        $listener = $this->getListener();
378
        // check direct messages
379 1
        return $listener instanceof EventListener && $listener->getEvent()->isDirectMessage() === true;
380
    }
381
}
382