Completed
Push — cleanup_nodb ( 09a9f6 )
by Armando
02:28
created

Command::isUserCommand()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
ccs 0
cts 2
cp 0
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
/**
3
 * This file is part of the TelegramBot package.
4
 *
5
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Longman\TelegramBot\Commands;
12
13
use Longman\TelegramBot\DB;
14
use Longman\TelegramBot\Entities\CallbackQuery;
15
use Longman\TelegramBot\Entities\ChosenInlineResult;
16
use Longman\TelegramBot\Entities\InlineQuery;
17
use Longman\TelegramBot\Entities\Message;
18
use Longman\TelegramBot\Entities\Update;
19
use Longman\TelegramBot\Request;
20
use Longman\TelegramBot\Telegram;
21
22
/**
23
 * Class Command
24
 *
25
 * Base class for commands. It includes some helper methods that can fetch data directly from the Update object.
26
 *
27
 * @method Message             getMessage()            Optional. New incoming message of any kind — text, photo, sticker, etc.
28
 * @method Message             getEditedMessage()      Optional. New version of a message that is known to the bot and was edited
29
 * @method Message             getChannelPost()        Optional. New post in the channel, can be any kind — text, photo, sticker, etc.
30
 * @method Message             getEditedChannelPost()  Optional. New version of a post in the channel that is known to the bot and was edited
31
 * @method InlineQuery         getInlineQuery()        Optional. New incoming inline query
32
 * @method ChosenInlineResult  getChosenInlineResult() Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
33
 * @method CallbackQuery       getCallbackQuery()      Optional. New incoming callback query
34
 */
35
abstract class Command
36
{
37
    /**
38
     * Telegram object
39
     *
40
     * @var \Longman\TelegramBot\Telegram
41
     */
42
    protected $telegram;
43
44
    /**
45
     * Update object
46
     *
47
     * @var \Longman\TelegramBot\Entities\Update
48
     */
49
    protected $update;
50
51
    /**
52
     * Name
53
     *
54
     * @var string
55
     */
56
    protected $name = '';
57
58
    /**
59
     * Description
60
     *
61
     * @var string
62
     */
63
    protected $description = 'Command description';
64
65
    /**
66
     * Usage
67
     *
68
     * @var string
69
     */
70
    protected $usage = 'Command usage';
71
72
    /**
73
     * Show in Help
74
     *
75
     * @var bool
76
     */
77
    protected $show_in_help = true;
78
79
    /**
80
     * Version
81
     *
82
     * @var string
83
     */
84
    protected $version = '1.0.0';
85
86
    /**
87
     * If this command is enabled
88
     *
89
     * @var boolean
90
     */
91
    protected $enabled = true;
92
93
    /**
94
     * If this command needs mysql
95
     *
96
     * @var boolean
97
     */
98
    protected $need_mysql = false;
99
100
    /**
101
     * Make sure this command only executes on a private chat.
102
     *
103
     * @var bool
104
     */
105
    protected $private_only = false;
106
107
    /**
108
     * Command config
109
     *
110
     * @var array
111
     */
112
    protected $config = [];
113
114
    /**
115
     * Constructor
116
     *
117
     * @param \Longman\TelegramBot\Telegram        $telegram
118
     * @param \Longman\TelegramBot\Entities\Update $update
119
     */
120 15
    public function __construct(Telegram $telegram, Update $update = null)
121
    {
122 15
        $this->telegram = $telegram;
123 15
        $this->setUpdate($update);
124 15
        $this->config = $telegram->getCommandConfig($this->name);
125 15
    }
126
127
    /**
128
     * Set update object
129
     *
130
     * @param \Longman\TelegramBot\Entities\Update $update
131
     *
132
     * @return \Longman\TelegramBot\Commands\Command
133
     */
134 15
    public function setUpdate(Update $update = null)
135
    {
136 15
        if ($update !== null) {
137 1
            $this->update = $update;
138
        }
139
140 15
        return $this;
141
    }
142
143
    /**
144
     * Pre-execute command
145
     *
146
     * @return \Longman\TelegramBot\Entities\ServerResponse
147
     * @throws \Longman\TelegramBot\Exception\TelegramException
148
     */
149
    public function preExecute()
150
    {
151
        if ($this->need_mysql && !($this->telegram->isDbEnabled() && DB::isDbConnected())) {
152
            return $this->executeNoDb();
153
        }
154
155
        if ($this->isPrivateOnly() && $this->removeNonPrivateMessage()) {
156
            $message = $this->getMessage();
157
            $chat    = $message->getChat();
158
            $user    = $message->getFrom();
159
160
            // @todo Deleting a message from a channel isn't working yet.
161
            if ($user !== null && !$chat->isChannel()) {
162
                return Request::sendMessage([
163
                    'chat_id'    => $user->getId(),
164
                    'parse_mode' => 'Markdown',
165
                    'text'       => sprintf(
166
                        "/%s command is only available in a private chat.\n(`%s`)",
167
                        $this->getName(),
168
                        $message->getText()
169
                    ),
170
                ]);
171
            }
172
173
            return Request::emptyResponse();
174
        }
175
176
        return $this->execute();
177
    }
178
179
    /**
180
     * Execute command
181
     *
182
     * @return \Longman\TelegramBot\Entities\ServerResponse
183
     * @throws \Longman\TelegramBot\Exception\TelegramException
184
     */
185
    abstract public function execute();
186
187
    /**
188
     * Execution if MySQL is required but not available
189
     *
190
     * @return \Longman\TelegramBot\Entities\ServerResponse
191
     * @throws \Longman\TelegramBot\Exception\TelegramException
192
     */
193 View Code Duplication
    public function executeNoDb()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
194
    {
195
        //Preparing message
196
        $message = $this->getMessage();
197
        $chat_id = $message->getChat()->getId();
198
199
        $data = [
200
            'chat_id' => $chat_id,
201
            'text'    => 'Sorry no database connection, unable to execute "' . $this->name . '" command.',
202
        ];
203
204
        return Request::sendMessage($data);
205
    }
206
207
    /**
208
     * Get update object
209
     *
210
     * @return \Longman\TelegramBot\Entities\Update
211
     */
212 1
    public function getUpdate()
213
    {
214 1
        return $this->update;
215
    }
216
217
    /**
218
     * Relay any non-existing function calls to Update object.
219
     *
220
     * This is purely a helper method to make requests from within execute() method easier.
221
     *
222
     * @param string $name
223
     * @param array  $arguments
224
     *
225
     * @return Command
226
     */
227 1
    public function __call($name, array $arguments)
228
    {
229 1
        if ($this->update === null) {
230 1
            return null;
231
        }
232 1
        return call_user_func_array([$this->update, $name], $arguments);
233
    }
234
235
    /**
236
     * Get command config
237
     *
238
     * Look for config $name if found return it, if not return null.
239
     * If $name is not set return all set config.
240
     *
241
     * @param string|null $name
242
     *
243
     * @return array|mixed|null
244
     */
245 1
    public function getConfig($name = null)
246
    {
247 1
        if ($name === null) {
248 1
            return $this->config;
249
        }
250 1
        if (isset($this->config[$name])) {
251 1
            return $this->config[$name];
252
        }
253
254 1
        return null;
255
    }
256
257
    /**
258
     * Get telegram object
259
     *
260
     * @return \Longman\TelegramBot\Telegram
261
     */
262 1
    public function getTelegram()
263
    {
264 1
        return $this->telegram;
265
    }
266
267
    /**
268
     * Get usage
269
     *
270
     * @return string
271
     */
272 1
    public function getUsage()
273
    {
274 1
        return $this->usage;
275
    }
276
277
    /**
278
     * Get version
279
     *
280
     * @return string
281
     */
282 1
    public function getVersion()
283
    {
284 1
        return $this->version;
285
    }
286
287
    /**
288
     * Get description
289
     *
290
     * @return string
291
     */
292 1
    public function getDescription()
293
    {
294 1
        return $this->description;
295
    }
296
297
    /**
298
     * Get name
299
     *
300
     * @return string
301
     */
302 1
    public function getName()
303
    {
304 1
        return $this->name;
305
    }
306
307
    /**
308
     * Get Show in Help
309
     *
310
     * @return bool
311
     */
312 1
    public function showInHelp()
313
    {
314 1
        return $this->show_in_help;
315
    }
316
317
    /**
318
     * Check if command is enabled
319
     *
320
     * @return bool
321
     */
322 1
    public function isEnabled()
323
    {
324 1
        return $this->enabled;
325
    }
326
327
    /**
328
     * If this command is intended for private chats only.
329
     *
330
     * @return bool
331
     */
332
    public function isPrivateOnly()
333
    {
334
        return $this->private_only;
335
    }
336
337
    /**
338
     * If this is a SystemCommand
339
     *
340
     * @return bool
341
     */
342
    public function isSystemCommand()
343
    {
344
        return ($this instanceof SystemCommand);
345
    }
346
347
    /**
348
     * If this is an AdminCommand
349
     *
350
     * @return bool
351
     */
352
    public function isAdminCommand()
353
    {
354
        return ($this instanceof AdminCommand);
355
    }
356
357
    /**
358
     * If this is a UserCommand
359
     *
360
     * @return bool
361
     */
362
    public function isUserCommand()
363
    {
364
        return ($this instanceof UserCommand);
365
    }
366
367
    /**
368
     * Delete the current message if it has been called in a non-private chat.
369
     *
370
     * @return bool
371
     */
372
    protected function removeNonPrivateMessage()
373
    {
374
        $message = $this->getMessage();
375
        $chat    = $message->getChat();
376
377
        if (!$chat->isPrivateChat()) {
378
            // Delete the falsely called command message.
379
            Request::deleteMessage([
380
                'chat_id'    => $chat->getId(),
381
                'message_id' => $message->getMessageId(),
382
            ]);
383
384
            return true;
385
        }
386
387
        return false;
388
    }
389
390
}
391