Completed
Pull Request — master (#540)
by
unknown
10:30
created

CommandBus::resolveCommandObject()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 17
cts 17
cp 1
rs 8.439
c 0
b 0
f 0
cc 5
eloc 14
nc 7
nop 1
crap 5
1
<?php
2
3
namespace Telegram\Bot\Commands;
4
5
use Telegram\Bot\Answers\AnswerBus;
6
use Telegram\Bot\Api;
7
use Telegram\Bot\Objects\Update;
8
use Telegram\Bot\Exceptions\TelegramSDKException;
9
10
/**
11
 * Class CommandBus.
12
 */
13
class CommandBus extends AnswerBus
14
{
15
    /**
16
     * @var Command[] Holds all commands.
17
     */
18
    protected $commands = [];
19
20
    /**
21
     * @var Command[] Holds all commands' aliases.
22
     */
23
    protected $commandAliases = [];
24
25
    /**
26
     * Instantiate Command Bus.
27
     *
28
     * @param Api $telegram
29
     *
30
     * @throws TelegramSDKException
31
     */
32 92
    public function __construct(Api $telegram)
33
    {
34 92
        $this->telegram = $telegram;
35 92
    }
36
37
    /**
38
     * Returns the list of commands.
39
     *
40
     * @return array
41
     */
42 10
    public function getCommands()
43
    {
44 10
        return $this->commands;
45
    }
46
47
    /**
48
     * Add a list of commands.
49
     *
50
     * @param array $commands
51
     *
52
     * @return CommandBus
53
     */
54 8
    public function addCommands(array $commands)
55
    {
56 8
        foreach ($commands as $command) {
57 8
            $this->addCommand($command);
58 8
        }
59
60 8
        return $this;
61
    }
62
63
    /**
64
     * Add a command to the commands list.
65
     *
66
     * @param CommandInterface|string $command Either an object or full path to the command class.
67
     *
68
     * @throws TelegramSDKException
69
     *
70
     * @return CommandBus
71
     */
72 20
    public function addCommand($command)
73
    {
74 20
        $command = $this->resolveCommandObject($command);
75
76
        /*
77
         * At this stage we definitely have a proper command to use.
78
         *
79
         * @var Command $command
80
         */
81 16
        $this->commands[$command->getName()] = $command;
82
83 16
        $aliases = $command->getAliases();
84
85 16
        if (empty($aliases)) {
86 16
            return $this;
87
        }
88
89
        foreach ($command->getAliases() as $alias) {
90 View Code Duplication
            if (isset($this->commands[$alias])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
91
                throw new TelegramSDKException(sprintf(
92
                    '[Error] Alias [%s] conflicts with command name of "%s" try with another name or remove this alias from the list.',
93
                    $alias,
94
                    get_class($command)
95
                ));
96
            }
97
98 View Code Duplication
            if (isset($this->commandAliases[$alias])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
99
                throw new TelegramSDKException(sprintf(
100
                    '[Error] Alias [%s] conflicts with another command\'s alias list: "%s", try with another name or remove this alias from the list.',
101
                    $alias,
102
                    get_class($command)
103
                ));
104
            }
105
106
            $this->commandAliases[$alias] = $command;
107
        }
108
109
        return $this;
110
111
112
    }
113
114
    /**
115
     * Remove a command from the list.
116
     *
117
     * @param $name
118
     *
119
     * @return CommandBus
120
     */
121 4
    public function removeCommand($name)
122
    {
123 4
        unset($this->commands[$name]);
124
125 4
        return $this;
126
    }
127
128
    /**
129
     * Removes a list of commands.
130
     *
131
     * @param array $names
132
     *
133
     * @return CommandBus
134
     */
135 2
    public function removeCommands(array $names)
136
    {
137 2
        foreach ($names as $name) {
138 2
            $this->removeCommand($name);
139 2
        }
140
141 2
        return $this;
142
    }
143
144
    /**
145
     * Parse a Command for a Match.
146
     *
147
     * @param $text
148
     *
149
     * @throws \InvalidArgumentException
150
     *
151
     * @return array
152
     */
153 16
    public function parseCommand($text)
154
    {
155 16
        if (trim($text) === '') {
156 2
            throw new \InvalidArgumentException('Message is empty, Cannot parse for command');
157
        }
158
159 14
        preg_match('/^\/([^\s@]+)@?(\S+)?\s?(.*)$/s', $text, $matches);
160
161 14
        return $matches;
162
    }
163
164
    /**
165
     * Handles Inbound Messages and Executes Appropriate Command.
166
     *
167
     * @param $message
168
     * @param $update
169
     *
170
     * @throws TelegramSDKException
171
     *
172
     * @return Update
173
     */
174 8
    protected function handler($message, Update $update)
175
    {
176 8
        $match = $this->parseCommand($message);
177 8
        if (!empty($match)) {
178 8
            $command = strtolower($match[1]); //All commands must be lowercase.
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
179
//            $bot = (!empty($match[2])) ? $match[2] : '';
180 8
            $arguments = $match[3];
181
182 8
            $this->execute($command, $arguments, $update);
183 8
        }
184
185 8
        return $update;
186
    }
187
188
    /**
189
     * Execute the command.
190
     *
191
     * @param $name
192
     * @param $arguments
193
     * @param $message
194
     *
195
     * @return mixed
196
     */
197 10
    protected function execute($name, $arguments, $message)
198
    {
199 10
        if (array_key_exists($name, $this->commands)) {
200 6
            return $this->commands[$name]->make($this->telegram, $arguments, $message);
201 4
        } elseif (array_key_exists($name, $this->commandAliases)) {
202
            return $this->commandAliases[$name]->make($this->telegram, $arguments, $message);
203 4
        } elseif (array_key_exists('help', $this->commands)) {
204
            return $this->commands['help']->make($this->telegram, $arguments, $message);
205
        }
206
207 4
        return 'Ok';
208
    }
209
210
    /**
211
     * @param $command
212
     * @return object
213
     * @throws \Telegram\Bot\Exceptions\TelegramSDKException
214
     */
215 20
    private function resolveCommandObject($command)
216
    {
217 20
        if (! is_object($command)) {
218 12
            if (! class_exists($command)) {
219 2
                throw new TelegramSDKException(sprintf('Command class "%s" not found! Please make sure the class exists.', $command));
220
            }
221
222 10
            if ($this->telegram->hasContainer()) {
223 2
                $command = $this->buildDependencyInjectedAnswer($command);
224 2
            } else {
225 8
                $command = new $command();
226
            }
227 10
        }
228
229 18
        if (!($command instanceof CommandInterface)) {
230
231 2
            throw new TelegramSDKException(
232 2
                sprintf(
233 2
                    'Command class "%s" should be an instance of "Telegram\Bot\Commands\CommandInterface"',
234 2
                    get_class($command)
235 2
                )
236 2
            );
237
        }
238
239 16
        return $command;
240
    }
241
}
242