GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

Command::isSystemCommand()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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