Completed
Pull Request — master (#51)
by
unknown
03:04
created

CommandHandler   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 103
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 90.32%

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 2
dl 0
loc 103
ccs 28
cts 31
cp 0.9032
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A initCommands() 0 17 3
B processCommands() 0 19 5
A addCommand() 0 4 1
A addCommands() 0 6 2
A addMessageCommand() 0 4 1
A addCallbackCommand() 0 4 1
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
/*
22
 * \class CommandHandler
23
 * \brief Handle all bot commands.
24
 * \details Add commands, check if commands trigger a user update.
25
 */
26
trait CommandHandler
27
{
28
    /**
29
     * \addtogroup Commands
30
     * \brief Bots command and usage.
31
     * @{
32
     */
33
34
    /** @internal
35
     * \brief Contains all command used by the bot. */
36
    private $_commands = [];
37
38
    /**
39
     * @internal
40
     * \brief Initialize commands to speed up processing.
41
     * \details Get all command that the bot handle, and put them in priority.
42
     */
43 3
    protected function initCommands()
44
    {
45 3
        $commands_temp = $this->_commands;
46 3
        $this->_commands = [];
47
48
        // Iterate over each
49 3
        foreach ($commands_temp as $command) {
50 1
            $this->_commands[$command::$type][] = $command;
51
        }
52
53 3
        foreach ($this->_commands as $index => $array) {
54
        // Sort them by priority
55 1
            uasort($this->_commands[$index], function ($array, $b) {
56
                return $a::$priority <=> $b::$priority;    
0 ignored issues
show
Bug introduced by
The variable $a does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
57 1
            });
58
        }
59 3
    }
60
61
    /**
62
     * @internal
63
     * \brief Process updates prioritizing bot's commands over the general methods (e.g. BaseBot::processMessage())
64
     * @param array $update Update to process.
65
     * @return bool True if this update trigger any command.
66
     */
67 5
    protected function processCommands(array $update) : bool
68
    {
69
        // For each command active (checked by initCommands())
70 5
        foreach ($this->_commands as $entity => $commands) {
71 3
            foreach ($commands as $command) {
72
                // If the update type is right and the update triggered a command
73 3
                if (isset($update[$entity]) && $command->checkCommand($update[$entity])) {
74 3
                    $entity = new $command::$object_class($update[$entity]);
75 3
                    $this->_chat_id = $entity->getChatID();
0 ignored issues
show
Bug introduced by
The property _chat_id does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
76 3
                    $command->getScript()($this, $entity);
77
                    // Return the id as we already processed this update
78 3
                    return true;
79
                }
80
            }
81
        }
82
83
        // Return -1 because this update didn't trigger any command.
84 2
        return false;
85
    }
86
87
    /**
88
     * \brief Add a command to the bot.
89
     * @param BasicCommand $command Command to add. Must be an object that inherits BasicCommand class.
90
     */
91 2
    public function addCommand(BasicCommand $command)
92
    {
93 2
        $this->_commands[] = $command;
94 2
    }
95
96
    /**
97
     * \brief Add various commands at once.
98
     * @param ...BasicCommand $commands The commands to add.
0 ignored issues
show
Documentation introduced by
The doc-type ...BasicCommand could not be parsed: Unknown type name "...BasicCommand" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
99
     */
100 1
    public function addCommands(BasicCommand ...$commands)
101
    {
102 1
      foreach ($commands as $command) {
103 1
            $this->addCommand($command);
104
        }
105 1
    }
106
107
    /**
108
     * \brief Add a message command to the bot.
109
     * @param string $command The command that will trigger the function (e.g. start).
110
     * @param callable $script The function that will be triggered by a command.
111
     */
112 1
    public function addMessageCommand(string $command, callable $script)
113
    {
114 1
      $this->_commands[] = new MessageCommand($command, $script);
115 1
    }
116
117
    /**
118
     * \brief Add a callback command to the bot.
119
     * @param string $data The data that will trigger the function.
120
     * @param callable $script The function that will be triggered by the data.
121
     */
122
    public function addCallbackCommand(string $data, callable $script)
123
    {
124
      $this->_commands[] = new CallbackCommand($data, $script);
125
    }
126
127
    /** @} */
128
}
129