MessageRegexCommand::checkCommand()   B
last analyzed

Complexity

Conditions 5
Paths 8

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 0
cts 8
cp 0
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 5
nc 8
nop 1
crap 30
1
<?php
2
3
/*
4
 * This file is part of the PhpBotFramework.
5
 *
6
 * PhpBotFramework is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as
8
 * published by the Free Software Foundation, version 3.
9
 *
10
 * PhpBotFramework is distributed in the hope that it will be useful, but
11
 * WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public License
16
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17
 */
18
19
namespace PhpBotFramework\Commands;
20
21
use PhpBotFramework\Entities\Message;
22
23
/**
24
 * \addtogroup Commands
25
 * @{
26
 */
27
28
/** \class MessageRegexCommand
29
 */
30
class MessageRegexCommand extends BasicCommand
31
{
32
    /** @} */
33
34
    private $regex_rule;
35
36
    /**
37
     * \brief Add a function that will be executed everytime a message contain a command
38
     * that match the regular expression.
39
     *
40
     * \details Use this syntax:
41
     *
42
     *     addMessageCommandRegex("number\d", function($bot, $message, $result) {
43
     *         $bot->sendMessage("You sent me a number"); });
44
     * @param string $regex_rule Regex rule that will called for evalueting the command received.
45
     * @param callable $script The function that will be triggered by a command.
46
     * Must take an object(the bot) and an array(the message received).
47
     */
48
    public function __construct(string $regex_rule, callable $script)
49
    {
50
        $this->script = $script;
51
        $this->regex_rule = $regex_rule;
52
    }
53
54
    /**
55
     * @internal
56
     * \brief Process the message to check if it triggers a command of this type.
57
     * @param array $message Message to process.
58
     * @return bool True if the message triggered a command.
59
     */
60
    public function checkCommand(array $message) : bool
61
    {
62
        // If the message contains a bot command at the start
63
        $message_is_command = (isset($message['entities']) && $message['entities'][0]['type'] === 'bot_command') ? true : false;
64
65
        // Use preg_match to check if it is true
66
        if ($message_is_command && preg_match("/{$this->regex_rule}/", substr($message['text'], $message['entities'][0]['offset'] + 1, $message['entities'][0]['length']))) {
67
                    return true;
68
        }
69
70
        return false;
71
    }
72
}
73