Completed
Pull Request — master (#481)
by Armando
04:27 queued 02:02
created

DB   D

Complexity

Total Complexity 115

Size/Duplication

Total Lines 1139
Duplicated Lines 11.06 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 30.52%

Importance

Changes 0
Metric Value
wmc 115
lcom 1
cbo 9
dl 126
loc 1139
ccs 152
cts 498
cp 0.3052
rs 4.4102
c 0
b 0
f 0

21 Methods

Rating   Name   Duplication   Size   Complexity  
B initialize() 0 28 3
A externalInitialize() 0 18 2
A defineTables() 0 21 3
A isDbConnected() 0 4 1
A getPdo() 0 4 1
B selectTelegramUpdate() 0 33 6
A getTimestamp() 0 8 2
B selectMessages() 0 27 4
A entitiesArrayToJson() 0 13 2
C insertTelegramUpdate() 0 38 8
B insertUser() 0 57 5
B insertChat() 0 47 4
D insertRequest() 48 101 17
B insertInlineQueryRequest() 39 39 4
B insertChosenInlineResultRequest() 39 39 4
B insertCallbackQueryRequest() 0 61 6
F insertMessageRequest() 0 158 11
B insertEditedMessageRequest() 0 55 5
F selectChats() 0 92 19
B getTelegramRequestCount() 0 28 3
B insertTelegramRequest() 0 31 5

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like DB often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DB, and based on these observations, apply Extract Interface, too.

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
 * Written by Marco Boretto <[email protected]>
10
 */
11
12
namespace Longman\TelegramBot;
13
14
use Longman\TelegramBot\Entities\CallbackQuery;
15
use Longman\TelegramBot\Entities\Chat;
16
use Longman\TelegramBot\Entities\ChosenInlineResult;
17
use Longman\TelegramBot\Entities\InlineQuery;
18
use Longman\TelegramBot\Entities\Message;
19
use Longman\TelegramBot\Entities\ReplyToMessage;
20
use Longman\TelegramBot\Entities\Update;
21
use Longman\TelegramBot\Entities\User;
22
use Longman\TelegramBot\Exception\TelegramException;
23
use PDO;
24
use PDOException;
25
26
class DB
27
{
28
    /**
29
     * MySQL credentials
30
     *
31
     * @var array
32
     */
33
    static protected $mysql_credentials = [];
34
35
    /**
36
     * PDO object
37
     *
38
     * @var PDO
39
     */
40
    static protected $pdo;
41
42
    /**
43
     * Table prefix
44
     *
45
     * @var string
46
     */
47
    static protected $table_prefix;
48
49
    /**
50
     * Telegram class object
51
     *
52
     * @var \Longman\TelegramBot\Telegram
53
     */
54
    static protected $telegram;
55
56
    /**
57
     * Initialize
58
     *
59
     * @param array                         $credentials  Database connection details
60
     * @param \Longman\TelegramBot\Telegram $telegram     Telegram object to connect with this object
61
     * @param string                        $table_prefix Table prefix
62
     * @param string                        $encoding     Database character encoding
63
     *
64
     * @return PDO PDO database object
65
     * @throws \Longman\TelegramBot\Exception\TelegramException
66
     */
67 9
    public static function initialize(
68
        array $credentials,
69
        Telegram $telegram,
70
        $table_prefix = null,
71
        $encoding = 'utf8mb4'
72
    ) {
73 9
        if (empty($credentials)) {
74
            throw new TelegramException('MySQL credentials not provided!');
75
        }
76
77 9
        $dsn     = 'mysql:host=' . $credentials['host'] . ';dbname=' . $credentials['database'];
78 9
        $options = [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . $encoding];
79
        try {
80 9
            $pdo = new PDO($dsn, $credentials['user'], $credentials['password'], $options);
81 9
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
82
        } catch (PDOException $e) {
83
            throw new TelegramException($e->getMessage());
84
        }
85
86 9
        self::$pdo               = $pdo;
87 9
        self::$telegram          = $telegram;
88 9
        self::$mysql_credentials = $credentials;
89 9
        self::$table_prefix      = $table_prefix;
90
91 9
        self::defineTables();
92
93 9
        return self::$pdo;
94
    }
95
96
    /**
97
     * External Initialize
98
     *
99
     * Let you use the class with an external already existing Pdo Mysql connection.
100
     *
101
     * @param PDO                           $external_pdo_connection PDO database object
102
     * @param \Longman\TelegramBot\Telegram $telegram                Telegram object to connect with this object
103
     * @param string                        $table_prefix            Table prefix
104
     *
105
     * @return PDO PDO database object
106
     * @throws \Longman\TelegramBot\Exception\TelegramException
107
     */
108
    public static function externalInitialize(
109
        $external_pdo_connection,
110
        Telegram $telegram,
111
        $table_prefix = null
112
    ) {
113
        if ($external_pdo_connection === null) {
114
            throw new TelegramException('MySQL external connection not provided!');
115
        }
116
117
        self::$pdo               = $external_pdo_connection;
118
        self::$telegram          = $telegram;
119
        self::$mysql_credentials = [];
120
        self::$table_prefix      = $table_prefix;
121
122
        self::defineTables();
123
124
        return self::$pdo;
125
    }
126
127
    /**
128
     * Define all the tables with the proper prefix
129
     */
130 9
    protected static function defineTables()
131
    {
132
        $tables = [
133 9
            'callback_query',
134
            'chat',
135
            'chosen_inline_result',
136
            'edited_message',
137
            'inline_query',
138
            'message',
139
            'request_limiter',
140
            'telegram_update',
141
            'user',
142
            'user_chat',
143
        ];
144 9
        foreach ($tables as $table) {
145 9
            $table_name = 'TB_' . strtoupper($table);
146 9
            if (!defined($table_name)) {
147 1
                define($table_name, self::$table_prefix . $table);
148
            }
149
        }
150 9
    }
151
152
    /**
153
     * Check if database connection has been created
154
     *
155
     * @return bool
156
     */
157 9
    public static function isDbConnected()
158
    {
159 9
        return self::$pdo !== null;
160
    }
161
162
    /**
163
     * Get the PDO object of the connected database
164
     *
165
     * @return \PDO
166
     */
167
    public static function getPdo()
168
    {
169
        return self::$pdo;
170
    }
171
172
    /**
173
     * Fetch update(s) from DB
174
     *
175
     * @param int $limit Limit the number of updates to fetch
176
     * @param int $id    Check for unique update id
177
     *
178
     * @return array|bool Fetched data or false if not connected
179
     * @throws \Longman\TelegramBot\Exception\TelegramException
180
     */
181
    public static function selectTelegramUpdate($limit = null, $id = null)
182
    {
183
        if (!self::isDbConnected()) {
184
            return false;
185
        }
186
187
        try {
188
            $sql = 'SELECT `id` FROM `' . TB_TELEGRAM_UPDATE . '`';
189
190
            if ($id !== null) {
191
                $sql .= ' WHERE `id` = :id';
192
            }
193
194
            $sql .= ' ORDER BY `id` DESC';
195
196
            if ($limit !== null) {
197
                $sql .= ' LIMIT :limit';
198
            }
199
200
            $sth = self::$pdo->prepare($sql);
201
            $sth->bindParam(':limit', $limit, PDO::PARAM_INT);
202
203
            if ($id !== null) {
204
                $sth->bindParam(':id', $id, PDO::PARAM_INT);
205
            }
206
207
            $sth->execute();
208
209
            return $sth->fetchAll(PDO::FETCH_ASSOC);
210
        } catch (PDOException $e) {
211
            throw new TelegramException($e->getMessage());
212
        }
213
    }
214
215
    /**
216
     * Fetch message(s) from DB
217
     *
218
     * @param int $limit Limit the number of messages to fetch
219
     *
220
     * @return array|bool Fetched data or false if not connected
221
     * @throws \Longman\TelegramBot\Exception\TelegramException
222
     */
223
    public static function selectMessages($limit = null)
224
    {
225
        if (!self::isDbConnected()) {
226
            return false;
227
        }
228
229
        try {
230
            $sql = '
231
                SELECT *
232
                FROM `' . TB_MESSAGE . '`
233
                WHERE `update_id` != 0
234
                ORDER BY `message_id` DESC
235
            ';
236
237
            if ($limit !== null) {
238
                $sql .= 'LIMIT :limit';
239
            }
240
241
            $sth = self::$pdo->prepare($sql);
242
            $sth->bindParam(':limit', $limit, PDO::PARAM_INT);
243
            $sth->execute();
244
245
            return $sth->fetchAll(PDO::FETCH_ASSOC);
246
        } catch (PDOException $e) {
247
            throw new TelegramException($e->getMessage());
248
        }
249
    }
250
251
    /**
252
     * Convert from unix timestamp to timestamp
253
     *
254
     * @param int $time Unix timestamp (if null, current timestamp is used)
255
     *
256
     * @return string
257
     */
258 7
    protected static function getTimestamp($time = null)
259
    {
260 7
        if ($time === null) {
261 6
            $time = time();
262
        }
263
264 7
        return date('Y-m-d H:i:s', $time);
265
    }
266
267
    /**
268
     * Convert array of Entity items to a JSON array
269
     *
270
     * @todo Find a better way, as json_* functions are very heavy
271
     *
272
     * @param array|null $entities
273
     * @param mixed      $default
274
     *
275
     * @return mixed
276
     */
277 6
    public static function entitiesArrayToJson($entities, $default = null)
278
    {
279 6
        if (!is_array($entities)) {
280 6
            return $default;
281
        }
282
283
        //Convert each Entity item into an object based on its JSON reflection
284
        $json_entities = array_map(function ($entity) {
285
            return json_decode($entity, true);
286
        }, $entities);
287
288
        return json_encode($json_entities);
289
    }
290
291
    /**
292
     * Insert entry to telegram_update table
293
     *
294
     * @param int $id
295
     * @param int $chat_id
296
     * @param int $message_id
297
     * @param int $inline_query_id
298
     * @param int $chosen_inline_result_id
299
     * @param int $callback_query_id
300
     * @param int $edited_message_id
301
     *
302
     * @return bool If the insert was successful
303
     * @throws \Longman\TelegramBot\Exception\TelegramException
304
     */
305
    public static function insertTelegramUpdate(
306
        $id,
307
        $chat_id,
308
        $message_id,
309
        $inline_query_id,
310
        $chosen_inline_result_id,
311
        $callback_query_id,
312
        $edited_message_id
313
    ) {
314
        if ($message_id === null && $inline_query_id === null && $chosen_inline_result_id === null && $callback_query_id === null && $edited_message_id === null) {
315
            throw new TelegramException('message_id, inline_query_id, chosen_inline_result_id, callback_query_id, edited_message_id are all null');
316
        }
317
318
        if (!self::isDbConnected()) {
319
            return false;
320
        }
321
322
        try {
323
            $sth = self::$pdo->prepare('
324
                INSERT IGNORE INTO `' . TB_TELEGRAM_UPDATE . '`
325
                (`id`, `chat_id`, `message_id`, `inline_query_id`, `chosen_inline_result_id`, `callback_query_id`, `edited_message_id`)
326
                VALUES
327
                (:id, :chat_id, :message_id, :inline_query_id, :chosen_inline_result_id, :callback_query_id, :edited_message_id)
328
            ');
329
330
            $sth->bindParam(':id', $id, PDO::PARAM_INT);
331
            $sth->bindParam(':chat_id', $chat_id, PDO::PARAM_INT);
332
            $sth->bindParam(':message_id', $message_id, PDO::PARAM_INT);
333
            $sth->bindParam(':inline_query_id', $inline_query_id, PDO::PARAM_INT);
334
            $sth->bindParam(':chosen_inline_result_id', $chosen_inline_result_id, PDO::PARAM_INT);
335
            $sth->bindParam(':callback_query_id', $callback_query_id, PDO::PARAM_INT);
336
            $sth->bindParam(':edited_message_id', $edited_message_id, PDO::PARAM_INT);
337
338
            return $sth->execute();
339
        } catch (PDOException $e) {
340
            throw new TelegramException($e->getMessage());
341
        }
342
    }
343
344
    /**
345
     * Insert users and save their connection to chats
346
     *
347
     * @param  \Longman\TelegramBot\Entities\User $user
348
     * @param  string                             $date
349
     * @param  \Longman\TelegramBot\Entities\Chat $chat
350
     *
351
     * @return bool If the insert was successful
352
     * @throws \Longman\TelegramBot\Exception\TelegramException
353
     */
354 6
    public static function insertUser(User $user, $date, Chat $chat = null)
355
    {
356 6
        if (!self::isDbConnected()) {
357
            return false;
358
        }
359
360 6
        $user_id    = $user->getId();
361 6
        $username   = $user->getUsername();
362 6
        $first_name = $user->getFirstName();
363 6
        $last_name  = $user->getLastName();
364
365
        try {
366 6
            $sth = self::$pdo->prepare('
367 6
                INSERT INTO `' . TB_USER . '`
368
                (`id`, `username`, `first_name`, `last_name`, `created_at`, `updated_at`)
369
                VALUES
370
                (:id, :username, :first_name, :last_name, :date, :date)
371
                ON DUPLICATE KEY UPDATE
372
                    `username`   = :username,
373
                    `first_name` = :first_name,
374
                    `last_name`  = :last_name,
375
                    `updated_at` = :date
376
            ');
377
378 6
            $sth->bindParam(':id', $user_id, PDO::PARAM_INT);
379 6
            $sth->bindParam(':username', $username, PDO::PARAM_STR, 255);
380 6
            $sth->bindParam(':first_name', $first_name, PDO::PARAM_STR, 255);
381 6
            $sth->bindParam(':last_name', $last_name, PDO::PARAM_STR, 255);
382 6
            $sth->bindParam(':date', $date, PDO::PARAM_STR);
383
384 6
            $status = $sth->execute();
385
        } catch (PDOException $e) {
386
            throw new TelegramException($e->getMessage());
387
        }
388
389
        //insert also the relationship to the chat into user_chat table
390 6
        if ($chat instanceof Chat) {
391 6
            $chat_id = $chat->getId();
392
            try {
393 6
                $sth = self::$pdo->prepare('
394 6
                    INSERT IGNORE INTO `' . TB_USER_CHAT . '`
395
                    (`user_id`, `chat_id`)
396
                    VALUES
397
                    (:user_id, :chat_id)
398
                ');
399
400 6
                $sth->bindParam(':user_id', $user_id, PDO::PARAM_INT);
401 6
                $sth->bindParam(':chat_id', $chat_id, PDO::PARAM_INT);
402
403 6
                $status = $sth->execute();
404
            } catch (PDOException $e) {
405
                throw new TelegramException($e->getMessage());
406
            }
407
        }
408
409 6
        return $status;
410
    }
411
412
    /**
413
     * Insert chat
414
     *
415
     * @param  \Longman\TelegramBot\Entities\Chat $chat
416
     * @param  string                             $date
417
     * @param  int                                $migrate_to_chat_id
418
     *
419
     * @return bool If the insert was successful
420
     * @throws \Longman\TelegramBot\Exception\TelegramException
421
     */
422 6
    public static function insertChat(Chat $chat, $date, $migrate_to_chat_id = null)
423
    {
424 6
        if (!self::isDbConnected()) {
425
            return false;
426
        }
427
428 6
        $chat_id                             = $chat->getId();
429 6
        $chat_title                          = $chat->getTitle();
430 6
        $chat_username                       = $chat->getUsername();
431 6
        $chat_type                           = $chat->getType();
432 6
        $chat_all_members_are_administrators = $chat->getAllMembersAreAdministrators();
433
434
        try {
435 6
            $sth = self::$pdo->prepare('
436 6
                INSERT IGNORE INTO `' . TB_CHAT . '`
437
                (`id`, `type`, `title`, `username`, `all_members_are_administrators`, `created_at` ,`updated_at`, `old_id`)
438
                VALUES
439
                (:id, :type, :title, :username, :all_members_are_administrators, :date, :date, :oldid)
440
                ON DUPLICATE KEY UPDATE
441
                    `type`                           = :type,
442
                    `title`                          = :title,
443
                    `username`                       = :username,
444
                    `all_members_are_administrators` = :all_members_are_administrators,
445
                    `updated_at`                     = :date
446
            ');
447
448 6
            if ($migrate_to_chat_id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $migrate_to_chat_id of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
449
                $chat_type = 'supergroup';
450
451
                $sth->bindParam(':id', $migrate_to_chat_id, PDO::PARAM_INT);
452
                $sth->bindParam(':oldid', $chat_id, PDO::PARAM_INT);
453
            } else {
454 6
                $sth->bindParam(':id', $chat_id, PDO::PARAM_INT);
455 6
                $sth->bindParam(':oldid', $migrate_to_chat_id, PDO::PARAM_INT);
456
            }
457
458 6
            $sth->bindParam(':type', $chat_type, PDO::PARAM_INT);
459 6
            $sth->bindParam(':title', $chat_title, PDO::PARAM_STR, 255);
460 6
            $sth->bindParam(':username', $chat_username, PDO::PARAM_STR, 255);
461 6
            $sth->bindParam(':all_members_are_administrators', $chat_all_members_are_administrators, PDO::PARAM_INT);
462 6
            $sth->bindParam(':date', $date, PDO::PARAM_STR);
463
464 6
            return $sth->execute();
465
        } catch (PDOException $e) {
466
            throw new TelegramException($e->getMessage());
467
        }
468
    }
469
470
    /**
471
     * Insert request into database
472
     *
473
     * @todo self::$pdo->lastInsertId() - unsafe usage if expected previous insert fails?
474
     *
475
     * @param \Longman\TelegramBot\Entities\Update $update
476
     *
477
     * @return bool
478
     * @throws \Longman\TelegramBot\Exception\TelegramException
479
     */
480
    public static function insertRequest(Update $update)
481
    {
482
        if (!self::isDbConnected()) {
483
            return false;
484
        }
485
486
        $update_id   = $update->getUpdateId();
487
        $update_type = $update->getUpdateType();
488
489
        if (count(self::selectTelegramUpdate(1, $update_id)) === 1) {
490
            throw new TelegramException('Duplicate update received!');
491
        }
492
493
        if ($update_type === 'message') {
494
            $message = $update->getMessage();
495
496 View Code Duplication
            if (self::insertMessageRequest($message)) {
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...
497
                $message_id = $message->getMessageId();
498
                $chat_id    = $message->getChat()->getId();
499
500
                return self::insertTelegramUpdate($update_id, $chat_id, $message_id, null, null, null, null);
501
            }
502 View Code Duplication
        } elseif ($update_type === 'edited_message') {
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...
503
            $edited_message = $update->getEditedMessage();
504
505
            if (self::insertEditedMessageRequest($edited_message)) {
506
                $chat_id                 = $edited_message->getChat()->getId();
507
                $edited_message_local_id = self::$pdo->lastInsertId();
508
509
                return self::insertTelegramUpdate(
510
                    $update_id,
511
                    $chat_id,
512
                    null,
513
                    null,
514
                    null,
515
                    null,
516
                    $edited_message_local_id
517
                );
518
            }
519
        } elseif ($update_type === 'channel_post') {
520
            $channel_post = $update->getChannelPost();
521
522 View Code Duplication
            if (self::insertMessageRequest($channel_post)) {
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...
523
                $message_id = $channel_post->getMessageId();
524
                $chat_id    = $channel_post->getChat()->getId();
525
526
                return self::insertTelegramUpdate($update_id, $chat_id, $message_id, null, null, null, null);
527
            }
528 View Code Duplication
        } elseif ($update_type === 'edited_channel_post') {
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...
529
            $edited_channel_post = $update->getEditedChannelPost();
530
531
            if (self::insertEditedMessageRequest($edited_channel_post)) {
532
                $chat_id                      = $edited_channel_post->getChat()->getId();
533
                $edited_channel_post_local_id = self::$pdo->lastInsertId();
534
535
                return self::insertTelegramUpdate(
536
                    $update_id,
537
                    $chat_id,
538
                    null,
539
                    null,
540
                    null,
541
                    null,
542
                    $edited_channel_post_local_id
543
                );
544
            }
545
        } elseif ($update_type === 'inline_query') {
546
            $inline_query = $update->getInlineQuery();
547
548
            if (self::insertInlineQueryRequest($inline_query)) {
549
                $inline_query_id = $inline_query->getId();
550
551
                return self::insertTelegramUpdate($update_id, null, null, $inline_query_id, null, null, null);
552
            }
553
        } elseif ($update_type === 'chosen_inline_result') {
554
            $chosen_inline_result = $update->getChosenInlineResult();
555
556
            if (self::insertChosenInlineResultRequest($chosen_inline_result)) {
557
                $chosen_inline_result_local_id = self::$pdo->lastInsertId();
558
559
                return self::insertTelegramUpdate(
560
                    $update_id,
561
                    null,
562
                    null,
563
                    null,
564
                    $chosen_inline_result_local_id,
565
                    null,
566
                    null
567
                );
568
            }
569
        } elseif ($update_type === 'callback_query') {
570
            $callback_query = $update->getCallbackQuery();
571
572
            if (self::insertCallbackQueryRequest($callback_query)) {
573
                $callback_query_id = $callback_query->getId();
574
575
                return self::insertTelegramUpdate($update_id, null, null, null, null, $callback_query_id, null);
576
            }
577
        }
578
579
        return false;
580
    }
581
582
    /**
583
     * Insert inline query request into database
584
     *
585
     * @param \Longman\TelegramBot\Entities\InlineQuery $inline_query
586
     *
587
     * @return bool If the insert was successful
588
     * @throws \Longman\TelegramBot\Exception\TelegramException
589
     */
590 View Code Duplication
    public static function insertInlineQueryRequest(InlineQuery $inline_query)
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...
591
    {
592
        if (!self::isDbConnected()) {
593
            return false;
594
        }
595
596
        try {
597
            $sth = self::$pdo->prepare('
598
                INSERT IGNORE INTO `' . TB_INLINE_QUERY . '`
599
                (`id`, `user_id`, `location`, `query`, `offset`, `created_at`)
600
                VALUES
601
                (:inline_query_id, :user_id, :location, :query, :param_offset, :created_at)
602
            ');
603
604
            $date            = self::getTimestamp();
605
            $inline_query_id = $inline_query->getId();
606
            $from            = $inline_query->getFrom();
607
            $user_id         = null;
608
            if ($from instanceof User) {
609
                $user_id = $from->getId();
610
                self::insertUser($from, $date);
611
            }
612
613
            $location = $inline_query->getLocation();
614
            $query    = $inline_query->getQuery();
615
            $offset   = $inline_query->getOffset();
616
617
            $sth->bindParam(':inline_query_id', $inline_query_id, PDO::PARAM_INT);
618
            $sth->bindParam(':user_id', $user_id, PDO::PARAM_INT);
619
            $sth->bindParam(':location', $location, PDO::PARAM_STR);
620
            $sth->bindParam(':query', $query, PDO::PARAM_STR);
621
            $sth->bindParam(':param_offset', $offset, PDO::PARAM_STR);
622
            $sth->bindParam(':created_at', $date, PDO::PARAM_STR);
623
624
            return $sth->execute();
625
        } catch (PDOException $e) {
626
            throw new TelegramException($e->getMessage());
627
        }
628
    }
629
630
    /**
631
     * Insert chosen inline result request into database
632
     *
633
     * @param \Longman\TelegramBot\Entities\ChosenInlineResult $chosen_inline_result
634
     *
635
     * @return bool If the insert was successful
636
     * @throws \Longman\TelegramBot\Exception\TelegramException
637
     */
638 View Code Duplication
    public static function insertChosenInlineResultRequest(ChosenInlineResult $chosen_inline_result)
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...
639
    {
640
        if (!self::isDbConnected()) {
641
            return false;
642
        }
643
644
        try {
645
            $sth = self::$pdo->prepare('
646
                INSERT INTO `' . TB_CHOSEN_INLINE_RESULT . '`
647
                (`result_id`, `user_id`, `location`, `inline_message_id`, `query`, `created_at`)
648
                VALUES
649
                (:result_id, :user_id, :location, :inline_message_id, :query, :created_at)
650
            ');
651
652
            $date      = self::getTimestamp();
653
            $result_id = $chosen_inline_result->getResultId();
654
            $from      = $chosen_inline_result->getFrom();
655
            $user_id   = null;
656
            if ($from instanceof User) {
657
                $user_id = $from->getId();
658
                self::insertUser($from, $date);
659
            }
660
661
            $location          = $chosen_inline_result->getLocation();
662
            $inline_message_id = $chosen_inline_result->getInlineMessageId();
663
            $query             = $chosen_inline_result->getQuery();
664
665
            $sth->bindParam(':result_id', $result_id, PDO::PARAM_STR);
666
            $sth->bindParam(':user_id', $user_id, PDO::PARAM_INT);
667
            $sth->bindParam(':location', $location, PDO::PARAM_STR);
668
            $sth->bindParam(':inline_message_id', $inline_message_id, PDO::PARAM_STR);
669
            $sth->bindParam(':query', $query, PDO::PARAM_STR);
670
            $sth->bindParam(':created_at', $date, PDO::PARAM_STR);
671
672
            return $sth->execute();
673
        } catch (PDOException $e) {
674
            throw new TelegramException($e->getMessage());
675
        }
676
    }
677
678
    /**
679
     * Insert callback query request into database
680
     *
681
     * @param \Longman\TelegramBot\Entities\CallbackQuery $callback_query
682
     *
683
     * @return bool If the insert was successful
684
     * @throws \Longman\TelegramBot\Exception\TelegramException
685
     */
686
    public static function insertCallbackQueryRequest(CallbackQuery $callback_query)
687
    {
688
        if (!self::isDbConnected()) {
689
            return false;
690
        }
691
692
        try {
693
            $sth = self::$pdo->prepare('
694
                INSERT IGNORE INTO `' . TB_CALLBACK_QUERY . '`
695
                (`id`, `user_id`, `chat_id`, `message_id`, `inline_message_id`, `data`, `created_at`)
696
                VALUES
697
                (:callback_query_id, :user_id, :chat_id, :message_id, :inline_message_id, :data, :created_at)
698
            ');
699
700
            $date              = self::getTimestamp();
701
            $callback_query_id = $callback_query->getId();
702
            $from              = $callback_query->getFrom();
703
            $user_id           = null;
704
            if ($from instanceof User) {
705
                $user_id = $from->getId();
706
                self::insertUser($from, $date);
707
            }
708
709
            $message    = $callback_query->getMessage();
710
            $chat_id    = null;
711
            $message_id = null;
712
            if ($message instanceof Message) {
713
                $chat_id    = $message->getChat()->getId();
714
                $message_id = $message->getMessageId();
715
716
                $is_message = self::$pdo->query('
717
                    SELECT *
718
                    FROM `' . TB_MESSAGE . '`
719
                    WHERE `id` = ' . $message_id . '
720
                      AND `chat_id` = ' . $chat_id . '
721
                    LIMIT 1
722
                ')->rowCount();
723
724
                if ($is_message) {
725
                    self::insertEditedMessageRequest($message);
726
                } else {
727
                    self::insertMessageRequest($message);
728
                }
729
            }
730
731
            $inline_message_id = $callback_query->getInlineMessageId();
732
            $data              = $callback_query->getData();
733
734
            $sth->bindParam(':callback_query_id', $callback_query_id, PDO::PARAM_INT);
735
            $sth->bindParam(':user_id', $user_id, PDO::PARAM_INT);
736
            $sth->bindParam(':chat_id', $chat_id, PDO::PARAM_INT);
737
            $sth->bindParam(':message_id', $message_id, PDO::PARAM_INT);
738
            $sth->bindParam(':inline_message_id', $inline_message_id, PDO::PARAM_STR);
739
            $sth->bindParam(':data', $data, PDO::PARAM_STR);
740
            $sth->bindParam(':created_at', $date, PDO::PARAM_STR);
741
742
            return $sth->execute();
743
        } catch (PDOException $e) {
744
            throw new TelegramException($e->getMessage());
745
        }
746
    }
747
748
    /**
749
     * Insert Message request in db
750
     *
751
     * @param \Longman\TelegramBot\Entities\Message $message
752
     *
753
     * @return bool If the insert was successful
754
     * @throws \Longman\TelegramBot\Exception\TelegramException
755
     */
756 6
    public static function insertMessageRequest(Message $message)
757
    {
758 6
        if (!self::isDbConnected()) {
759
            return false;
760
        }
761
762 6
        $from = $message->getFrom();
763 6
        $chat = $message->getChat();
764
765 6
        $chat_id = $chat->getId();
766
767 6
        $date = self::getTimestamp($message->getDate());
768
769 6
        $forward_from            = $message->getForwardFrom();
770 6
        $forward_from_chat       = $message->getForwardFromChat();
771 6
        $forward_from_message_id = $message->getForwardFromMessageId();
772 6
        $photo                   = self::entitiesArrayToJson($message->getPhoto(), '');
773 6
        $entities                = self::entitiesArrayToJson($message->getEntities(), null);
774 6
        $new_chat_member         = $message->getNewChatMember();
775 6
        $new_chat_photo          = self::entitiesArrayToJson($message->getNewChatPhoto(), '');
776 6
        $left_chat_member        = $message->getLeftChatMember();
777 6
        $migrate_to_chat_id      = $message->getMigrateToChatId();
778
779
        //Insert chat, update chat id in case it migrated
780 6
        self::insertChat($chat, $date, $migrate_to_chat_id);
781
782
        //Insert user and the relation with the chat
783 6
        if (is_object($from)) {
784 6
            self::insertUser($from, $date, $chat);
785
        }
786
787
        //Insert the forwarded message user in users table
788 6
        if ($forward_from instanceof User) {
789
            $forward_date = self::getTimestamp($message->getForwardDate());
790
            self::insertUser($forward_from, $forward_date);
791
            $forward_from = $forward_from->getId();
792
        }
793
794 6
        if ($forward_from_chat instanceof Chat) {
795
            $forward_date = self::getTimestamp($message->getForwardDate());
796
            self::insertChat($forward_from_chat, $forward_date);
797
            $forward_from_chat = $forward_from_chat->getId();
798
        }
799
800
        //New and left chat member
801 6
        if ($new_chat_member instanceof User) {
802
            //Insert the new chat user
803
            self::insertUser($new_chat_member, $date, $chat);
804
            $new_chat_member = $new_chat_member->getId();
805 6
        } elseif ($left_chat_member instanceof User) {
806
            //Insert the left chat user
807
            self::insertUser($left_chat_member, $date, $chat);
808
            $left_chat_member = $left_chat_member->getId();
809
        }
810
811
        try {
812 6
            $sth = self::$pdo->prepare('
813 6
                INSERT IGNORE INTO `' . TB_MESSAGE . '`
814
                (
815
                    `id`, `user_id`, `chat_id`, `date`, `forward_from`, `forward_from_chat`, `forward_from_message_id`,
816
                    `forward_date`, `reply_to_chat`, `reply_to_message`, `text`, `entities`, `audio`, `document`,
817
                    `photo`, `sticker`, `video`, `voice`, `caption`, `contact`,
818
                    `location`, `venue`, `new_chat_member`, `left_chat_member`,
819
                    `new_chat_title`,`new_chat_photo`, `delete_chat_photo`, `group_chat_created`,
820
                    `supergroup_chat_created`, `channel_chat_created`,
821
                    `migrate_from_chat_id`, `migrate_to_chat_id`, `pinned_message`
822
                ) VALUES (
823
                    :message_id, :user_id, :chat_id, :date, :forward_from, :forward_from_chat, :forward_from_message_id,
824
                    :forward_date, :reply_to_chat, :reply_to_message, :text, :entities, :audio, :document,
825
                    :photo, :sticker, :video, :voice, :caption, :contact,
826
                    :location, :venue, :new_chat_member, :left_chat_member,
827
                    :new_chat_title, :new_chat_photo, :delete_chat_photo, :group_chat_created,
828
                    :supergroup_chat_created, :channel_chat_created,
829
                    :migrate_from_chat_id, :migrate_to_chat_id, :pinned_message
830
                )
831
            ');
832
833 6
            $message_id = $message->getMessageId();
834
835 6
            if (is_object($from)) {
836 6
                $from_id = $from->getId();
837
            } else {
838
                $from_id = null;
839
            }
840
841 6
            $reply_to_message    = $message->getReplyToMessage();
842 6
            $reply_to_message_id = null;
843 6
            if ($reply_to_message instanceof ReplyToMessage) {
844
                $reply_to_message_id = $reply_to_message->getMessageId();
845
                // please notice that, as explained in the documentation, reply_to_message don't contain other
846
                // reply_to_message field so recursion deep is 1
847
                self::insertMessageRequest($reply_to_message);
848
            }
849
850 6
            $text                    = $message->getText();
851 6
            $audio                   = $message->getAudio();
852 6
            $document                = $message->getDocument();
853 6
            $sticker                 = $message->getSticker();
854 6
            $video                   = $message->getVideo();
855 6
            $voice                   = $message->getVoice();
856 6
            $caption                 = $message->getCaption();
857 6
            $contact                 = $message->getContact();
858 6
            $location                = $message->getLocation();
859 6
            $venue                   = $message->getVenue();
860 6
            $new_chat_title          = $message->getNewChatTitle();
861 6
            $delete_chat_photo       = $message->getDeleteChatPhoto();
862 6
            $group_chat_created      = $message->getGroupChatCreated();
863 6
            $supergroup_chat_created = $message->getSupergroupChatCreated();
864 6
            $channel_chat_created    = $message->getChannelChatCreated();
865 6
            $migrate_from_chat_id    = $message->getMigrateFromChatId();
866 6
            $migrate_to_chat_id      = $message->getMigrateToChatId();
867 6
            $pinned_message          = $message->getPinnedMessage();
868
869 6
            $sth->bindParam(':chat_id', $chat_id, PDO::PARAM_INT);
870 6
            $sth->bindParam(':message_id', $message_id, PDO::PARAM_INT);
871 6
            $sth->bindParam(':user_id', $from_id, PDO::PARAM_INT);
872 6
            $sth->bindParam(':date', $date, PDO::PARAM_STR);
873 6
            $sth->bindParam(':forward_from', $forward_from, PDO::PARAM_INT);
874 6
            $sth->bindParam(':forward_from_chat', $forward_from_chat, PDO::PARAM_INT);
875 6
            $sth->bindParam(':forward_from_message_id', $forward_from_message_id, PDO::PARAM_INT);
876 6
            $sth->bindParam(':forward_date', $forward_date, PDO::PARAM_STR);
877
878 6
            $reply_to_chat_id = null;
879 6
            if ($reply_to_message_id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $reply_to_message_id of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
880
                $reply_to_chat_id = $chat_id;
881
            }
882
883 6
            $sth->bindParam(':reply_to_chat', $reply_to_chat_id, PDO::PARAM_INT);
884 6
            $sth->bindParam(':reply_to_message', $reply_to_message_id, PDO::PARAM_INT);
885 6
            $sth->bindParam(':text', $text, PDO::PARAM_STR);
886 6
            $sth->bindParam(':entities', $entities, PDO::PARAM_STR);
887 6
            $sth->bindParam(':audio', $audio, PDO::PARAM_STR);
888 6
            $sth->bindParam(':document', $document, PDO::PARAM_STR);
889 6
            $sth->bindParam(':photo', $photo, PDO::PARAM_STR);
890 6
            $sth->bindParam(':sticker', $sticker, PDO::PARAM_STR);
891 6
            $sth->bindParam(':video', $video, PDO::PARAM_STR);
892 6
            $sth->bindParam(':voice', $voice, PDO::PARAM_STR);
893 6
            $sth->bindParam(':caption', $caption, PDO::PARAM_STR);
894 6
            $sth->bindParam(':contact', $contact, PDO::PARAM_STR);
895 6
            $sth->bindParam(':location', $location, PDO::PARAM_STR);
896 6
            $sth->bindParam(':venue', $venue, PDO::PARAM_STR);
897 6
            $sth->bindParam(':new_chat_member', $new_chat_member, PDO::PARAM_INT);
898 6
            $sth->bindParam(':left_chat_member', $left_chat_member, PDO::PARAM_INT);
899 6
            $sth->bindParam(':new_chat_title', $new_chat_title, PDO::PARAM_STR);
900 6
            $sth->bindParam(':new_chat_photo', $new_chat_photo, PDO::PARAM_STR);
901 6
            $sth->bindParam(':delete_chat_photo', $delete_chat_photo, PDO::PARAM_INT);
902 6
            $sth->bindParam(':group_chat_created', $group_chat_created, PDO::PARAM_INT);
903 6
            $sth->bindParam(':supergroup_chat_created', $supergroup_chat_created, PDO::PARAM_INT);
904 6
            $sth->bindParam(':channel_chat_created', $channel_chat_created, PDO::PARAM_INT);
905 6
            $sth->bindParam(':migrate_from_chat_id', $migrate_from_chat_id, PDO::PARAM_INT);
906 6
            $sth->bindParam(':migrate_to_chat_id', $migrate_to_chat_id, PDO::PARAM_INT);
907 6
            $sth->bindParam(':pinned_message', $pinned_message, PDO::PARAM_STR);
908
909 6
            return $sth->execute();
910
        } catch (PDOException $e) {
911
            throw new TelegramException($e->getMessage());
912
        }
913
    }
914
915
    /**
916
     * Insert Edited Message request in db
917
     *
918
     * @param \Longman\TelegramBot\Entities\Message $edited_message
919
     *
920
     * @return bool If the insert was successful
921
     * @throws \Longman\TelegramBot\Exception\TelegramException
922
     */
923
    public static function insertEditedMessageRequest(Message $edited_message)
924
    {
925
        if (!self::isDbConnected()) {
926
            return false;
927
        }
928
929
        $from = $edited_message->getFrom();
930
        $chat = $edited_message->getChat();
931
932
        $chat_id = $chat->getId();
933
934
        $edit_date = self::getTimestamp($edited_message->getEditDate());
935
936
        $entities = self::entitiesArrayToJson($edited_message->getEntities(), null);
937
938
        //Insert chat
939
        self::insertChat($chat, $edit_date);
940
941
        //Insert user and the relation with the chat
942
        if (is_object($from)) {
943
            self::insertUser($from, $edit_date, $chat);
944
        }
945
946
        try {
947
            $sth = self::$pdo->prepare('
948
                INSERT IGNORE INTO `' . TB_EDITED_MESSAGE . '`
949
                (`chat_id`, `message_id`, `user_id`, `edit_date`, `text`, `entities`, `caption`)
950
                VALUES
951
                (:chat_id, :message_id, :user_id, :date, :text, :entities, :caption)
952
            ');
953
954
            $message_id = $edited_message->getMessageId();
955
956
            if (is_object($from)) {
957
                $from_id = $from->getId();
958
            } else {
959
                $from_id = null;
960
            }
961
962
            $text    = $edited_message->getText();
963
            $caption = $edited_message->getCaption();
964
965
            $sth->bindParam(':chat_id', $chat_id, PDO::PARAM_INT);
966
            $sth->bindParam(':message_id', $message_id, PDO::PARAM_INT);
967
            $sth->bindParam(':user_id', $from_id, PDO::PARAM_INT);
968
            $sth->bindParam(':date', $edit_date, PDO::PARAM_STR);
969
            $sth->bindParam(':text', $text, PDO::PARAM_STR);
970
            $sth->bindParam(':entities', $entities, PDO::PARAM_STR);
971
            $sth->bindParam(':caption', $caption, PDO::PARAM_STR);
972
973
            return $sth->execute();
974
        } catch (PDOException $e) {
975
            throw new TelegramException($e->getMessage());
976
        }
977
    }
978
979
    /**
980
     * Select Group and/or single Chats
981
     *
982
     * @param bool   $select_groups
983
     * @param bool   $select_super_groups
984
     * @param bool   $select_users
985
     * @param string $date_from
986
     * @param string $date_to
987
     * @param int    $chat_id
988
     * @param string $text
989
     *
990
     * @return array|bool (Selected chats or false if invalid arguments)
991
     * @throws \Longman\TelegramBot\Exception\TelegramException
992
     */
993
    public static function selectChats(
994
        $select_groups = true,
995
        $select_super_groups = true,
996
        $select_users = true,
997
        $date_from = null,
998
        $date_to = null,
999
        $chat_id = null,
1000
        $text = null
1001
    ) {
1002
        if (!self::isDbConnected()) {
1003
            return false;
1004
        }
1005
1006
        if (!$select_groups && !$select_users && !$select_super_groups) {
1007
            return false;
1008
        }
1009
1010
        try {
1011
            $query = '
1012
                SELECT * ,
1013
                ' . TB_CHAT . '.`id` AS `chat_id`,
1014
                ' . TB_CHAT . '.`created_at` AS `chat_created_at`,
1015
                ' . TB_CHAT . '.`updated_at` AS `chat_updated_at`
1016
            ';
1017
            if ($select_users) {
1018
                $query .= '
1019
                    , ' . TB_USER . '.`id` AS `user_id`
1020
                    FROM `' . TB_CHAT . '`
1021
                    LEFT JOIN `' . TB_USER . '`
1022
                    ON ' . TB_CHAT . '.`id`=' . TB_USER . '.`id`
1023
                ';
1024
            } else {
1025
                $query .= 'FROM `' . TB_CHAT . '`';
1026
            }
1027
1028
            //Building parts of query
1029
            $where  = [];
1030
            $tokens = [];
1031
1032
            if (!$select_groups || !$select_users || !$select_super_groups) {
1033
                $chat_or_user = [];
1034
1035
                $select_groups && $chat_or_user[] = TB_CHAT . '.`type` = "group"';
1036
                $select_super_groups && $chat_or_user[] = TB_CHAT . '.`type` = "supergroup"';
1037
                $select_users && $chat_or_user[] = TB_CHAT . '.`type` = "private"';
1038
1039
                $where[] = '(' . implode(' OR ', $chat_or_user) . ')';
1040
            }
1041
1042
            if (null !== $date_from) {
1043
                $where[]              = TB_CHAT . '.`updated_at` >= :date_from';
1044
                $tokens[':date_from'] = $date_from;
1045
            }
1046
1047
            if (null !== $date_to) {
1048
                $where[]            = TB_CHAT . '.`updated_at` <= :date_to';
1049
                $tokens[':date_to'] = $date_to;
1050
            }
1051
1052
            if (null !== $chat_id) {
1053
                $where[]            = TB_CHAT . '.`id` = :chat_id';
1054
                $tokens[':chat_id'] = $chat_id;
1055
            }
1056
1057
            if (null !== $text) {
1058
                if ($select_users) {
1059
                    $where[] = '(
1060
                        LOWER(' . TB_CHAT . '.`title`) LIKE :text
1061
                        OR LOWER(' . TB_USER . '.`first_name`) LIKE :text
1062
                        OR LOWER(' . TB_USER . '.`last_name`) LIKE :text
1063
                        OR LOWER(' . TB_USER . '.`username`) LIKE :text
1064
                    )';
1065
                } else {
1066
                    $where[] = 'LOWER(' . TB_CHAT . '.`title`) LIKE :text';
1067
                }
1068
                $tokens[':text'] = '%' . strtolower($text) . '%';
1069
            }
1070
1071
            if (!empty($where)) {
1072
                $query .= ' WHERE ' . implode(' AND ', $where);
1073
            }
1074
1075
            $query .= ' ORDER BY ' . TB_CHAT . '.`updated_at` ASC';
1076
1077
            $sth = self::$pdo->prepare($query);
1078
            $sth->execute($tokens);
1079
1080
            return $sth->fetchAll(PDO::FETCH_ASSOC);
1081
        } catch (PDOException $e) {
1082
            throw new TelegramException($e->getMessage());
1083
        }
1084
    }
1085
1086
    /**
1087
     * Get Telegram API request count for current chat / message
1088
     *
1089
     * @param integer $chat_id
1090
     * @param string  $inline_message_id
1091
     *
1092
     * @return array|bool (Array containing TOTAL and CURRENT fields or false on invalid arguments)
1093
     * @throws \Longman\TelegramBot\Exception\TelegramException
1094
     */
1095
    public static function getTelegramRequestCount($chat_id = null, $inline_message_id = null)
1096
    {
1097
        if (!self::isDbConnected()) {
1098
            return false;
1099
        }
1100
1101
        try {
1102
            $sth = self::$pdo->prepare('SELECT 
1103
                (SELECT COUNT(*) FROM `' . TB_REQUEST_LIMITER . '` WHERE `created_at` >= :date) as LIMIT_PER_SEC_ALL,
1104
                (SELECT COUNT(*) FROM `' . TB_REQUEST_LIMITER . '` WHERE ((`chat_id` = :chat_id AND `inline_message_id` IS NULL) OR (`inline_message_id` = :inline_message_id AND `chat_id` IS NULL)) AND `created_at` >= :date) as LIMIT_PER_SEC,
1105
                (SELECT COUNT(*) FROM `' . TB_REQUEST_LIMITER . '` WHERE `chat_id` = :chat_id AND `created_at` >= :date_minute) as LIMIT_PER_MINUTE
1106
            ');
1107
1108
            $date = self::getTimestamp();
1109
            $date_minute = self::getTimestamp(strtotime('-1 minute'));
1110
1111
            $sth->bindParam(':chat_id', $chat_id, \PDO::PARAM_STR);
1112
            $sth->bindParam(':inline_message_id', $inline_message_id, \PDO::PARAM_STR);
1113
            $sth->bindParam(':date', $date, \PDO::PARAM_STR);
1114
            $sth->bindParam(':date_minute', $date_minute, \PDO::PARAM_STR);
1115
1116
            $sth->execute();
1117
1118
            return $sth->fetch();
1119
        } catch (\Exception $e) {
1120
            throw new TelegramException($e->getMessage());
1121
        }
1122
    }
1123
1124
    /**
1125
     * Insert Telegram API request in db
1126
     *
1127
     * @param string $method
1128
     * @param array  $data
1129
     *
1130
     * @return bool If the insert was successful
1131
     * @throws \Longman\TelegramBot\Exception\TelegramException
1132
     */
1133
    public static function insertTelegramRequest($method, $data)
1134
    {
1135
        if (!self::isDbConnected()) {
1136
            return false;
1137
        }
1138
1139
        $chat_id = ((isset($data['chat_id'])) ? $data['chat_id'] : null);
1140
        $inline_message_id = (isset($data['inline_message_id']) ? $data['inline_message_id'] : null);
1141
1142
        try {
1143
            $sth = self::$pdo->prepare('INSERT INTO `' . TB_REQUEST_LIMITER . '`
1144
                (
1145
                `method`, `chat_id`, `inline_message_id`, `created_at`
1146
                )
1147
                VALUES (
1148
                :method, :chat_id, :inline_message_id, :date
1149
                );
1150
            ');
1151
1152
            $created_at = self::getTimestamp();
1153
1154
            $sth->bindParam(':chat_id', $chat_id, \PDO::PARAM_STR);
1155
            $sth->bindParam(':inline_message_id', $inline_message_id, \PDO::PARAM_STR);
1156
            $sth->bindParam(':method', $method, \PDO::PARAM_STR);
1157
            $sth->bindParam(':date', $created_at, \PDO::PARAM_STR);
1158
1159
            return $sth->execute();
1160
        } catch (\Exception $e) {
1161
            throw new TelegramException($e->getMessage());
1162
        }
1163
    }
1164
}
1165