Completed
Push — api_3.0_basic_changes ( 9bd403...4db909 )
by Armando
02:46
created

DB::insertInlineQueryRequest()   B

Complexity

Conditions 4
Paths 29

Size

Total Lines 39
Code Lines 25

Duplication

Lines 39
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 39
loc 39
ccs 0
cts 24
cp 0
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 25
nc 29
nop 1
crap 20
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 6
        $language_code  = $user->getLanguageCode();
365
366
        try {
367 6
            $sth = self::$pdo->prepare('
368 6
                INSERT INTO `' . TB_USER . '`
369
                (`id`, `username`, `first_name`, `last_name`, `language_code`, `created_at`, `updated_at`)
370
                VALUES
371
                (:id, :username, :first_name, :last_name, :language_code, :created_at, :updated_at)
372
                ON DUPLICATE KEY UPDATE
373
                    `username`       = VALUES(`username`),
374
                    `first_name`     = VALUES(`first_name`),
375
                    `last_name`      = VALUES(`last_name`),
376
                    `language_code`  = VALUES(`language_code`),
377
                    `updated_at`     = VALUES(`updated_at`)
378
            ');
379
380 6
            $sth->bindParam(':id', $user_id, PDO::PARAM_INT);
381 6
            $sth->bindParam(':username', $username, PDO::PARAM_STR, 255);
382 6
            $sth->bindParam(':first_name', $first_name, PDO::PARAM_STR, 255);
383 6
            $sth->bindParam(':last_name', $last_name, PDO::PARAM_STR, 255);
384 6
            $sth->bindParam(':language_code', $language_code, PDO::PARAM_STR, 10);
385 6
            $sth->bindParam(':created_at', $date, PDO::PARAM_STR);
386 6
            $sth->bindParam(':updated_at', $date, PDO::PARAM_STR);
387
388 6
            $status = $sth->execute();
389
        } catch (PDOException $e) {
390
            throw new TelegramException($e->getMessage());
391
        }
392
393
        //insert also the relationship to the chat into user_chat table
394 6
        if ($chat instanceof Chat) {
395 6
            $chat_id = $chat->getId();
396
            try {
397 6
                $sth = self::$pdo->prepare('
398 6
                    INSERT IGNORE INTO `' . TB_USER_CHAT . '`
399
                    (`user_id`, `chat_id`)
400
                    VALUES
401
                    (:user_id, :chat_id)
402
                ');
403
404 6
                $sth->bindParam(':user_id', $user_id, PDO::PARAM_INT);
405 6
                $sth->bindParam(':chat_id', $chat_id, PDO::PARAM_INT);
406
407 6
                $status = $sth->execute();
408
            } catch (PDOException $e) {
409
                throw new TelegramException($e->getMessage());
410
            }
411
        }
412
413 6
        return $status;
414
    }
415
416
    /**
417
     * Insert chat
418
     *
419
     * @param  \Longman\TelegramBot\Entities\Chat $chat
420
     * @param  string                             $date
421
     * @param  int                                $migrate_to_chat_id
422
     *
423
     * @return bool If the insert was successful
424
     * @throws \Longman\TelegramBot\Exception\TelegramException
425
     */
426 6
    public static function insertChat(Chat $chat, $date, $migrate_to_chat_id = null)
427
    {
428 6
        if (!self::isDbConnected()) {
429
            return false;
430
        }
431
432 6
        $chat_id                             = $chat->getId();
433 6
        $chat_title                          = $chat->getTitle();
434 6
        $chat_username                       = $chat->getUsername();
435 6
        $chat_type                           = $chat->getType();
436 6
        $chat_all_members_are_administrators = $chat->getAllMembersAreAdministrators();
437
438
        try {
439 6
            $sth = self::$pdo->prepare('
440 6
                INSERT IGNORE INTO `' . TB_CHAT . '`
441
                (`id`, `type`, `title`, `username`, `all_members_are_administrators`, `created_at` ,`updated_at`, `old_id`)
442
                VALUES
443
                (:id, :type, :title, :username, :all_members_are_administrators, :created_at, :updated_at, :oldid)
444
                ON DUPLICATE KEY UPDATE
445
                    `type`                           = VALUES(`type`),
446
                    `title`                          = VALUES(`title`),
447
                    `username`                       = VALUES(`username`),
448
                    `all_members_are_administrators` = VALUES(`all_members_are_administrators`),
449
                    `updated_at`                     = VALUES(`updated_at`)
450
            ');
451
452 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...
453
                $chat_type = 'supergroup';
454
455
                $sth->bindParam(':id', $migrate_to_chat_id, PDO::PARAM_INT);
456
                $sth->bindParam(':oldid', $chat_id, PDO::PARAM_INT);
457
            } else {
458 6
                $sth->bindParam(':id', $chat_id, PDO::PARAM_INT);
459 6
                $sth->bindParam(':oldid', $migrate_to_chat_id, PDO::PARAM_INT);
460
            }
461
462 6
            $sth->bindParam(':type', $chat_type, PDO::PARAM_INT);
463 6
            $sth->bindParam(':title', $chat_title, PDO::PARAM_STR, 255);
464 6
            $sth->bindParam(':username', $chat_username, PDO::PARAM_STR, 255);
465 6
            $sth->bindParam(':all_members_are_administrators', $chat_all_members_are_administrators, PDO::PARAM_INT);
466 6
            $sth->bindParam(':created_at', $date, PDO::PARAM_STR);
467 6
            $sth->bindParam(':updated_at', $date, PDO::PARAM_STR);
468
469 6
            return $sth->execute();
470
        } catch (PDOException $e) {
471
            throw new TelegramException($e->getMessage());
472
        }
473
    }
474
475
    /**
476
     * Insert request into database
477
     *
478
     * @todo self::$pdo->lastInsertId() - unsafe usage if expected previous insert fails?
479
     *
480
     * @param \Longman\TelegramBot\Entities\Update $update
481
     *
482
     * @return bool
483
     * @throws \Longman\TelegramBot\Exception\TelegramException
484
     */
485
    public static function insertRequest(Update $update)
486
    {
487
        if (!self::isDbConnected()) {
488
            return false;
489
        }
490
491
        $update_id   = $update->getUpdateId();
492
        $update_type = $update->getUpdateType();
493
494
        if (count(self::selectTelegramUpdate(1, $update_id)) === 1) {
495
            throw new TelegramException('Duplicate update received!');
496
        }
497
498
        if ($update_type === 'message') {
499
            $message = $update->getMessage();
500
501 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...
502
                $message_id = $message->getMessageId();
503
                $chat_id    = $message->getChat()->getId();
504
505
                return self::insertTelegramUpdate($update_id, $chat_id, $message_id, null, null, null, null);
506
            }
507 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...
508
            $edited_message = $update->getEditedMessage();
509
510
            if (self::insertEditedMessageRequest($edited_message)) {
511
                $chat_id                 = $edited_message->getChat()->getId();
512
                $edited_message_local_id = self::$pdo->lastInsertId();
513
514
                return self::insertTelegramUpdate(
515
                    $update_id,
516
                    $chat_id,
517
                    null,
518
                    null,
519
                    null,
520
                    null,
521
                    $edited_message_local_id
522
                );
523
            }
524
        } elseif ($update_type === 'channel_post') {
525
            $channel_post = $update->getChannelPost();
526
527 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...
528
                $message_id = $channel_post->getMessageId();
529
                $chat_id    = $channel_post->getChat()->getId();
530
531
                return self::insertTelegramUpdate($update_id, $chat_id, $message_id, null, null, null, null);
532
            }
533 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...
534
            $edited_channel_post = $update->getEditedChannelPost();
535
536
            if (self::insertEditedMessageRequest($edited_channel_post)) {
537
                $chat_id                      = $edited_channel_post->getChat()->getId();
538
                $edited_channel_post_local_id = self::$pdo->lastInsertId();
539
540
                return self::insertTelegramUpdate(
541
                    $update_id,
542
                    $chat_id,
543
                    null,
544
                    null,
545
                    null,
546
                    null,
547
                    $edited_channel_post_local_id
548
                );
549
            }
550
        } elseif ($update_type === 'inline_query') {
551
            $inline_query = $update->getInlineQuery();
552
553
            if (self::insertInlineQueryRequest($inline_query)) {
554
                $inline_query_id = $inline_query->getId();
555
556
                return self::insertTelegramUpdate($update_id, null, null, $inline_query_id, null, null, null);
557
            }
558
        } elseif ($update_type === 'chosen_inline_result') {
559
            $chosen_inline_result = $update->getChosenInlineResult();
560
561
            if (self::insertChosenInlineResultRequest($chosen_inline_result)) {
562
                $chosen_inline_result_local_id = self::$pdo->lastInsertId();
563
564
                return self::insertTelegramUpdate(
565
                    $update_id,
566
                    null,
567
                    null,
568
                    null,
569
                    $chosen_inline_result_local_id,
570
                    null,
571
                    null
572
                );
573
            }
574
        } elseif ($update_type === 'callback_query') {
575
            $callback_query = $update->getCallbackQuery();
576
577
            if (self::insertCallbackQueryRequest($callback_query)) {
578
                $callback_query_id = $callback_query->getId();
579
580
                return self::insertTelegramUpdate($update_id, null, null, null, null, $callback_query_id, null);
581
            }
582
        }
583
584
        return false;
585
    }
586
587
    /**
588
     * Insert inline query request into database
589
     *
590
     * @param \Longman\TelegramBot\Entities\InlineQuery $inline_query
591
     *
592
     * @return bool If the insert was successful
593
     * @throws \Longman\TelegramBot\Exception\TelegramException
594
     */
595 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...
596
    {
597
        if (!self::isDbConnected()) {
598
            return false;
599
        }
600
601
        try {
602
            $sth = self::$pdo->prepare('
603
                INSERT IGNORE INTO `' . TB_INLINE_QUERY . '`
604
                (`id`, `user_id`, `location`, `query`, `offset`, `created_at`)
605
                VALUES
606
                (:inline_query_id, :user_id, :location, :query, :param_offset, :created_at)
607
            ');
608
609
            $date            = self::getTimestamp();
610
            $inline_query_id = $inline_query->getId();
611
            $from            = $inline_query->getFrom();
612
            $user_id         = null;
613
            if ($from instanceof User) {
614
                $user_id = $from->getId();
615
                self::insertUser($from, $date);
616
            }
617
618
            $location = $inline_query->getLocation();
619
            $query    = $inline_query->getQuery();
620
            $offset   = $inline_query->getOffset();
621
622
            $sth->bindParam(':inline_query_id', $inline_query_id, PDO::PARAM_INT);
623
            $sth->bindParam(':user_id', $user_id, PDO::PARAM_INT);
624
            $sth->bindParam(':location', $location, PDO::PARAM_STR);
625
            $sth->bindParam(':query', $query, PDO::PARAM_STR);
626
            $sth->bindParam(':param_offset', $offset, PDO::PARAM_STR);
627
            $sth->bindParam(':created_at', $date, PDO::PARAM_STR);
628
629
            return $sth->execute();
630
        } catch (PDOException $e) {
631
            throw new TelegramException($e->getMessage());
632
        }
633
    }
634
635
    /**
636
     * Insert chosen inline result request into database
637
     *
638
     * @param \Longman\TelegramBot\Entities\ChosenInlineResult $chosen_inline_result
639
     *
640
     * @return bool If the insert was successful
641
     * @throws \Longman\TelegramBot\Exception\TelegramException
642
     */
643 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...
644
    {
645
        if (!self::isDbConnected()) {
646
            return false;
647
        }
648
649
        try {
650
            $sth = self::$pdo->prepare('
651
                INSERT INTO `' . TB_CHOSEN_INLINE_RESULT . '`
652
                (`result_id`, `user_id`, `location`, `inline_message_id`, `query`, `created_at`)
653
                VALUES
654
                (:result_id, :user_id, :location, :inline_message_id, :query, :created_at)
655
            ');
656
657
            $date      = self::getTimestamp();
658
            $result_id = $chosen_inline_result->getResultId();
659
            $from      = $chosen_inline_result->getFrom();
660
            $user_id   = null;
661
            if ($from instanceof User) {
662
                $user_id = $from->getId();
663
                self::insertUser($from, $date);
664
            }
665
666
            $location          = $chosen_inline_result->getLocation();
667
            $inline_message_id = $chosen_inline_result->getInlineMessageId();
668
            $query             = $chosen_inline_result->getQuery();
669
670
            $sth->bindParam(':result_id', $result_id, PDO::PARAM_STR);
671
            $sth->bindParam(':user_id', $user_id, PDO::PARAM_INT);
672
            $sth->bindParam(':location', $location, PDO::PARAM_STR);
673
            $sth->bindParam(':inline_message_id', $inline_message_id, PDO::PARAM_STR);
674
            $sth->bindParam(':query', $query, PDO::PARAM_STR);
675
            $sth->bindParam(':created_at', $date, PDO::PARAM_STR);
676
677
            return $sth->execute();
678
        } catch (PDOException $e) {
679
            throw new TelegramException($e->getMessage());
680
        }
681
    }
682
683
    /**
684
     * Insert callback query request into database
685
     *
686
     * @param \Longman\TelegramBot\Entities\CallbackQuery $callback_query
687
     *
688
     * @return bool If the insert was successful
689
     * @throws \Longman\TelegramBot\Exception\TelegramException
690
     */
691
    public static function insertCallbackQueryRequest(CallbackQuery $callback_query)
692
    {
693
        if (!self::isDbConnected()) {
694
            return false;
695
        }
696
697
        try {
698
            $sth = self::$pdo->prepare('
699
                INSERT IGNORE INTO `' . TB_CALLBACK_QUERY . '`
700
                (`id`, `user_id`, `chat_id`, `message_id`, `inline_message_id`, `data`, `created_at`)
701
                VALUES
702
                (:callback_query_id, :user_id, :chat_id, :message_id, :inline_message_id, :data, :created_at)
703
            ');
704
705
            $date              = self::getTimestamp();
706
            $callback_query_id = $callback_query->getId();
707
            $from              = $callback_query->getFrom();
708
            $user_id           = null;
709
            if ($from instanceof User) {
710
                $user_id = $from->getId();
711
                self::insertUser($from, $date);
712
            }
713
714
            $message    = $callback_query->getMessage();
715
            $chat_id    = null;
716
            $message_id = null;
717
            if ($message instanceof Message) {
718
                $chat_id    = $message->getChat()->getId();
719
                $message_id = $message->getMessageId();
720
721
                $is_message = self::$pdo->query('
722
                    SELECT *
723
                    FROM `' . TB_MESSAGE . '`
724
                    WHERE `id` = ' . $message_id . '
725
                      AND `chat_id` = ' . $chat_id . '
726
                    LIMIT 1
727
                ')->rowCount();
728
729
                if ($is_message) {
730
                    self::insertEditedMessageRequest($message);
731
                } else {
732
                    self::insertMessageRequest($message);
733
                }
734
            }
735
736
            $inline_message_id = $callback_query->getInlineMessageId();
737
            $data              = $callback_query->getData();
738
739
            $sth->bindParam(':callback_query_id', $callback_query_id, PDO::PARAM_INT);
740
            $sth->bindParam(':user_id', $user_id, PDO::PARAM_INT);
741
            $sth->bindParam(':chat_id', $chat_id, PDO::PARAM_INT);
742
            $sth->bindParam(':message_id', $message_id, PDO::PARAM_INT);
743
            $sth->bindParam(':inline_message_id', $inline_message_id, PDO::PARAM_STR);
744
            $sth->bindParam(':data', $data, PDO::PARAM_STR);
745
            $sth->bindParam(':created_at', $date, PDO::PARAM_STR);
746
747
            return $sth->execute();
748
        } catch (PDOException $e) {
749
            throw new TelegramException($e->getMessage());
750
        }
751
    }
752
753
    /**
754
     * Insert Message request in db
755
     *
756
     * @param \Longman\TelegramBot\Entities\Message $message
757
     *
758
     * @return bool If the insert was successful
759
     * @throws \Longman\TelegramBot\Exception\TelegramException
760
     */
761 6
    public static function insertMessageRequest(Message $message)
762
    {
763 6
        if (!self::isDbConnected()) {
764
            return false;
765
        }
766
767 6
        $from = $message->getFrom();
768 6
        $chat = $message->getChat();
769
770 6
        $chat_id = $chat->getId();
771
772 6
        $date = self::getTimestamp($message->getDate());
773
774 6
        $forward_from            = $message->getForwardFrom();
775 6
        $forward_from_chat       = $message->getForwardFromChat();
776 6
        $forward_from_message_id = $message->getForwardFromMessageId();
777 6
        $photo                   = self::entitiesArrayToJson($message->getPhoto(), '');
778 6
        $entities                = self::entitiesArrayToJson($message->getEntities(), null);
779 6
        $new_chat_members        = $message->getNewChatMembers();
780 6
        $left_chat_member        = $message->getLeftChatMember();
781 6
        $new_chat_photo          = self::entitiesArrayToJson($message->getNewChatPhoto(), '');
782 6
        $migrate_to_chat_id      = $message->getMigrateToChatId();
783
784
        //Insert chat, update chat id in case it migrated
785 6
        self::insertChat($chat, $date, $migrate_to_chat_id);
786
787
        //Insert user and the relation with the chat
788 6
        if (is_object($from)) {
789 6
            self::insertUser($from, $date, $chat);
790
        }
791
792
        //Insert the forwarded message user in users table
793 6
        if ($forward_from instanceof User) {
794
            $forward_date = self::getTimestamp($message->getForwardDate());
795
            self::insertUser($forward_from, $forward_date);
796
            $forward_from = $forward_from->getId();
797
        }
798
799 6
        if ($forward_from_chat instanceof Chat) {
800
            $forward_date = self::getTimestamp($message->getForwardDate());
801
            self::insertChat($forward_from_chat, $forward_date);
802
            $forward_from_chat = $forward_from_chat->getId();
803
        }
804
805
        //New and left chat member
806 6
        if (!empty($new_chat_members)) {
807
            foreach ($new_chat_members as $new_chat_member) {
808
                if ($new_chat_member instanceof User) {
809
                    //Insert the new chat user
810
                    self::insertUser($new_chat_member, $date, $chat);
811
                }
812
            }
813
814
            $new_chat_members = json_encode($new_chat_members);
815 6
        } elseif ($left_chat_member instanceof User) {
816
            //Insert the left chat user
817
            self::insertUser($left_chat_member, $date, $chat);
818
            $left_chat_member = $left_chat_member->getId();
819
        }
820
821
        try {
822 6
            $sth = self::$pdo->prepare('
823 6
                INSERT IGNORE INTO `' . TB_MESSAGE . '`
824
                (
825
                    `id`, `user_id`, `chat_id`, `date`, `forward_from`, `forward_from_chat`, `forward_from_message_id`,
826
                    `forward_date`, `reply_to_chat`, `reply_to_message`, `text`, `entities`, `audio`, `document`,
827
                    `photo`, `sticker`, `video`, `voice`, `video_note`, `caption`, `contact`,
828
                    `location`, `venue`, `new_chat_members`, `left_chat_member`,
829
                    `new_chat_title`,`new_chat_photo`, `delete_chat_photo`, `group_chat_created`,
830
                    `supergroup_chat_created`, `channel_chat_created`,
831
                    `migrate_from_chat_id`, `migrate_to_chat_id`, `pinned_message`
832
                ) VALUES (
833
                    :message_id, :user_id, :chat_id, :date, :forward_from, :forward_from_chat, :forward_from_message_id,
834
                    :forward_date, :reply_to_chat, :reply_to_message, :text, :entities, :audio, :document,
835
                    :photo, :sticker, :video, :voice, :video_note, :caption, :contact,
836
                    :location, :venue, :new_chat_members, :left_chat_member,
837
                    :new_chat_title, :new_chat_photo, :delete_chat_photo, :group_chat_created,
838
                    :supergroup_chat_created, :channel_chat_created,
839
                    :migrate_from_chat_id, :migrate_to_chat_id, :pinned_message
840
                )
841
            ');
842
843 6
            $message_id = $message->getMessageId();
844
845 6
            if (is_object($from)) {
846 6
                $from_id = $from->getId();
847
            } else {
848
                $from_id = null;
849
            }
850
851 6
            $reply_to_message    = $message->getReplyToMessage();
852 6
            $reply_to_message_id = null;
853 6
            if ($reply_to_message instanceof ReplyToMessage) {
854
                $reply_to_message_id = $reply_to_message->getMessageId();
855
                // please notice that, as explained in the documentation, reply_to_message don't contain other
856
                // reply_to_message field so recursion deep is 1
857
                self::insertMessageRequest($reply_to_message);
858
            }
859
860 6
            $text                    = $message->getText();
861 6
            $audio                   = $message->getAudio();
862 6
            $document                = $message->getDocument();
863 6
            $sticker                 = $message->getSticker();
864 6
            $video                   = $message->getVideo();
865 6
            $voice                   = $message->getVoice();
866 6
            $video_note              = $message->getVideoNote();
867 6
            $caption                 = $message->getCaption();
868 6
            $contact                 = $message->getContact();
869 6
            $location                = $message->getLocation();
870 6
            $venue                   = $message->getVenue();
871 6
            $new_chat_title          = $message->getNewChatTitle();
872 6
            $delete_chat_photo       = $message->getDeleteChatPhoto();
873 6
            $group_chat_created      = $message->getGroupChatCreated();
874 6
            $supergroup_chat_created = $message->getSupergroupChatCreated();
875 6
            $channel_chat_created    = $message->getChannelChatCreated();
876 6
            $migrate_from_chat_id    = $message->getMigrateFromChatId();
877 6
            $migrate_to_chat_id      = $message->getMigrateToChatId();
878 6
            $pinned_message          = $message->getPinnedMessage();
879
880 6
            $sth->bindParam(':chat_id', $chat_id, PDO::PARAM_INT);
881 6
            $sth->bindParam(':message_id', $message_id, PDO::PARAM_INT);
882 6
            $sth->bindParam(':user_id', $from_id, PDO::PARAM_INT);
883 6
            $sth->bindParam(':date', $date, PDO::PARAM_STR);
884 6
            $sth->bindParam(':forward_from', $forward_from, PDO::PARAM_INT);
885 6
            $sth->bindParam(':forward_from_chat', $forward_from_chat, PDO::PARAM_INT);
886 6
            $sth->bindParam(':forward_from_message_id', $forward_from_message_id, PDO::PARAM_INT);
887 6
            $sth->bindParam(':forward_date', $forward_date, PDO::PARAM_STR);
888
889 6
            $reply_to_chat_id = null;
890 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...
891
                $reply_to_chat_id = $chat_id;
892
            }
893
894 6
            $sth->bindParam(':reply_to_chat', $reply_to_chat_id, PDO::PARAM_INT);
895 6
            $sth->bindParam(':reply_to_message', $reply_to_message_id, PDO::PARAM_INT);
896 6
            $sth->bindParam(':text', $text, PDO::PARAM_STR);
897 6
            $sth->bindParam(':entities', $entities, PDO::PARAM_STR);
898 6
            $sth->bindParam(':audio', $audio, PDO::PARAM_STR);
899 6
            $sth->bindParam(':document', $document, PDO::PARAM_STR);
900 6
            $sth->bindParam(':photo', $photo, PDO::PARAM_STR);
901 6
            $sth->bindParam(':sticker', $sticker, PDO::PARAM_STR);
902 6
            $sth->bindParam(':video', $video, PDO::PARAM_STR);
903 6
            $sth->bindParam(':voice', $voice, PDO::PARAM_STR);
904 6
            $sth->bindParam(':video_note', $video_note, PDO::PARAM_STR);
905 6
            $sth->bindParam(':caption', $caption, PDO::PARAM_STR);
906 6
            $sth->bindParam(':contact', $contact, PDO::PARAM_STR);
907 6
            $sth->bindParam(':location', $location, PDO::PARAM_STR);
908 6
            $sth->bindParam(':venue', $venue, PDO::PARAM_STR);
909 6
            $sth->bindParam(':new_chat_members', $new_chat_members, PDO::PARAM_STR);
910 6
            $sth->bindParam(':left_chat_member', $left_chat_member, PDO::PARAM_INT);
911 6
            $sth->bindParam(':new_chat_title', $new_chat_title, PDO::PARAM_STR);
912 6
            $sth->bindParam(':new_chat_photo', $new_chat_photo, PDO::PARAM_STR);
913 6
            $sth->bindParam(':delete_chat_photo', $delete_chat_photo, PDO::PARAM_INT);
914 6
            $sth->bindParam(':group_chat_created', $group_chat_created, PDO::PARAM_INT);
915 6
            $sth->bindParam(':supergroup_chat_created', $supergroup_chat_created, PDO::PARAM_INT);
916 6
            $sth->bindParam(':channel_chat_created', $channel_chat_created, PDO::PARAM_INT);
917 6
            $sth->bindParam(':migrate_from_chat_id', $migrate_from_chat_id, PDO::PARAM_INT);
918 6
            $sth->bindParam(':migrate_to_chat_id', $migrate_to_chat_id, PDO::PARAM_INT);
919 6
            $sth->bindParam(':pinned_message', $pinned_message, PDO::PARAM_STR);
920
921 6
            return $sth->execute();
922
        } catch (PDOException $e) {
923
            throw new TelegramException($e->getMessage());
924
        }
925
    }
926
927
    /**
928
     * Insert Edited Message request in db
929
     *
930
     * @param \Longman\TelegramBot\Entities\Message $edited_message
931
     *
932
     * @return bool If the insert was successful
933
     * @throws \Longman\TelegramBot\Exception\TelegramException
934
     */
935
    public static function insertEditedMessageRequest(Message $edited_message)
936
    {
937
        if (!self::isDbConnected()) {
938
            return false;
939
        }
940
941
        $from = $edited_message->getFrom();
942
        $chat = $edited_message->getChat();
943
944
        $chat_id = $chat->getId();
945
946
        $edit_date = self::getTimestamp($edited_message->getEditDate());
947
948
        $entities = self::entitiesArrayToJson($edited_message->getEntities(), null);
949
950
        //Insert chat
951
        self::insertChat($chat, $edit_date);
952
953
        //Insert user and the relation with the chat
954
        if (is_object($from)) {
955
            self::insertUser($from, $edit_date, $chat);
956
        }
957
958
        try {
959
            $sth = self::$pdo->prepare('
960
                INSERT IGNORE INTO `' . TB_EDITED_MESSAGE . '`
961
                (`chat_id`, `message_id`, `user_id`, `edit_date`, `text`, `entities`, `caption`)
962
                VALUES
963
                (:chat_id, :message_id, :user_id, :edit_date, :text, :entities, :caption)
964
            ');
965
966
            $message_id = $edited_message->getMessageId();
967
968
            if (is_object($from)) {
969
                $from_id = $from->getId();
970
            } else {
971
                $from_id = null;
972
            }
973
974
            $text    = $edited_message->getText();
975
            $caption = $edited_message->getCaption();
976
977
            $sth->bindParam(':chat_id', $chat_id, PDO::PARAM_INT);
978
            $sth->bindParam(':message_id', $message_id, PDO::PARAM_INT);
979
            $sth->bindParam(':user_id', $from_id, PDO::PARAM_INT);
980
            $sth->bindParam(':edit_date', $edit_date, PDO::PARAM_STR);
981
            $sth->bindParam(':text', $text, PDO::PARAM_STR);
982
            $sth->bindParam(':entities', $entities, PDO::PARAM_STR);
983
            $sth->bindParam(':caption', $caption, PDO::PARAM_STR);
984
985
            return $sth->execute();
986
        } catch (PDOException $e) {
987
            throw new TelegramException($e->getMessage());
988
        }
989
    }
990
991
    /**
992
     * Select Group and/or single Chats
993
     *
994
     * @param bool   $select_groups
995
     * @param bool   $select_super_groups
996
     * @param bool   $select_users
997
     * @param string $date_from
998
     * @param string $date_to
999
     * @param int    $chat_id
1000
     * @param string $text
1001
     *
1002
     * @return array|bool (Selected chats or false if invalid arguments)
1003
     * @throws \Longman\TelegramBot\Exception\TelegramException
1004
     */
1005
    public static function selectChats(
1006
        $select_groups = true,
1007
        $select_super_groups = true,
1008
        $select_users = true,
1009
        $date_from = null,
1010
        $date_to = null,
1011
        $chat_id = null,
1012
        $text = null
1013
    ) {
1014
        if (!self::isDbConnected()) {
1015
            return false;
1016
        }
1017
1018
        if (!$select_groups && !$select_users && !$select_super_groups) {
1019
            return false;
1020
        }
1021
1022
        try {
1023
            $query = '
1024
                SELECT * ,
1025
                ' . TB_CHAT . '.`id` AS `chat_id`,
1026
                ' . TB_CHAT . '.`created_at` AS `chat_created_at`,
1027
                ' . TB_CHAT . '.`updated_at` AS `chat_updated_at`
1028
            ';
1029
            if ($select_users) {
1030
                $query .= '
1031
                    , ' . TB_USER . '.`id` AS `user_id`
1032
                    FROM `' . TB_CHAT . '`
1033
                    LEFT JOIN `' . TB_USER . '`
1034
                    ON ' . TB_CHAT . '.`id`=' . TB_USER . '.`id`
1035
                ';
1036
            } else {
1037
                $query .= 'FROM `' . TB_CHAT . '`';
1038
            }
1039
1040
            //Building parts of query
1041
            $where  = [];
1042
            $tokens = [];
1043
1044
            if (!$select_groups || !$select_users || !$select_super_groups) {
1045
                $chat_or_user = [];
1046
1047
                $select_groups && $chat_or_user[] = TB_CHAT . '.`type` = "group"';
1048
                $select_super_groups && $chat_or_user[] = TB_CHAT . '.`type` = "supergroup"';
1049
                $select_users && $chat_or_user[] = TB_CHAT . '.`type` = "private"';
1050
1051
                $where[] = '(' . implode(' OR ', $chat_or_user) . ')';
1052
            }
1053
1054
            if (null !== $date_from) {
1055
                $where[]              = TB_CHAT . '.`updated_at` >= :date_from';
1056
                $tokens[':date_from'] = $date_from;
1057
            }
1058
1059
            if (null !== $date_to) {
1060
                $where[]            = TB_CHAT . '.`updated_at` <= :date_to';
1061
                $tokens[':date_to'] = $date_to;
1062
            }
1063
1064
            if (null !== $chat_id) {
1065
                $where[]            = TB_CHAT . '.`id` = :chat_id';
1066
                $tokens[':chat_id'] = $chat_id;
1067
            }
1068
1069
            if (null !== $text) {
1070
                if ($select_users) {
1071
                    $where[] = '(
1072
                        LOWER(' . TB_CHAT . '.`title`) LIKE :text
1073
                        OR LOWER(' . TB_USER . '.`first_name`) LIKE :text
1074
                        OR LOWER(' . TB_USER . '.`last_name`) LIKE :text
1075
                        OR LOWER(' . TB_USER . '.`username`) LIKE :text
1076
                    )';
1077
                } else {
1078
                    $where[] = 'LOWER(' . TB_CHAT . '.`title`) LIKE :text';
1079
                }
1080
                $tokens[':text'] = '%' . strtolower($text) . '%';
1081
            }
1082
1083
            if (!empty($where)) {
1084
                $query .= ' WHERE ' . implode(' AND ', $where);
1085
            }
1086
1087
            $query .= ' ORDER BY ' . TB_CHAT . '.`updated_at` ASC';
1088
1089
            $sth = self::$pdo->prepare($query);
1090
            $sth->execute($tokens);
1091
1092
            return $sth->fetchAll(PDO::FETCH_ASSOC);
1093
        } catch (PDOException $e) {
1094
            throw new TelegramException($e->getMessage());
1095
        }
1096
    }
1097
1098
    /**
1099
     * Get Telegram API request count for current chat / message
1100
     *
1101
     * @param integer $chat_id
1102
     * @param string  $inline_message_id
1103
     *
1104
     * @return array|bool (Array containing TOTAL and CURRENT fields or false on invalid arguments)
1105
     * @throws \Longman\TelegramBot\Exception\TelegramException
1106
     */
1107
    public static function getTelegramRequestCount($chat_id = null, $inline_message_id = null)
1108
    {
1109
        if (!self::isDbConnected()) {
1110
            return false;
1111
        }
1112
1113
        try {
1114
            $sth = self::$pdo->prepare('SELECT 
1115
                (SELECT COUNT(*) FROM `' . TB_REQUEST_LIMITER . '` WHERE `created_at` >= :created_at_1) as LIMIT_PER_SEC_ALL,
1116
                (SELECT COUNT(*) FROM `' . TB_REQUEST_LIMITER . '` WHERE `created_at` >= :created_at_2 AND ((`chat_id` = :chat_id_1 AND `inline_message_id` IS NULL) OR (`inline_message_id` = :inline_message_id AND `chat_id` IS NULL))) as LIMIT_PER_SEC,
1117
                (SELECT COUNT(*) FROM `' . TB_REQUEST_LIMITER . '` WHERE `created_at` >= :created_at_minute AND `chat_id` = :chat_id_2) as LIMIT_PER_MINUTE
1118
            ');
1119
1120
            $date = self::getTimestamp();
1121
            $date_minute = self::getTimestamp(strtotime('-1 minute'));
1122
1123
            $sth->bindParam(':chat_id_1', $chat_id, \PDO::PARAM_STR);
1124
            $sth->bindParam(':chat_id_2', $chat_id, \PDO::PARAM_STR);
1125
            $sth->bindParam(':inline_message_id', $inline_message_id, \PDO::PARAM_STR);
1126
            $sth->bindParam(':created_at_1', $date, \PDO::PARAM_STR);
1127
            $sth->bindParam(':created_at_2', $date, \PDO::PARAM_STR);
1128
            $sth->bindParam(':created_at_minute', $date_minute, \PDO::PARAM_STR);
1129
1130
            $sth->execute();
1131
1132
            return $sth->fetch();
1133
        } catch (\Exception $e) {
1134
            throw new TelegramException($e->getMessage());
1135
        }
1136
    }
1137
1138
    /**
1139
     * Insert Telegram API request in db
1140
     *
1141
     * @param string $method
1142
     * @param array  $data
1143
     *
1144
     * @return bool If the insert was successful
1145
     * @throws \Longman\TelegramBot\Exception\TelegramException
1146
     */
1147
    public static function insertTelegramRequest($method, $data)
1148
    {
1149
        if (!self::isDbConnected()) {
1150
            return false;
1151
        }
1152
1153
        $chat_id = ((isset($data['chat_id'])) ? $data['chat_id'] : null);
1154
        $inline_message_id = (isset($data['inline_message_id']) ? $data['inline_message_id'] : null);
1155
1156
        try {
1157
            $sth = self::$pdo->prepare('INSERT INTO `' . TB_REQUEST_LIMITER . '`
1158
                (
1159
                `method`, `chat_id`, `inline_message_id`, `created_at`
1160
                )
1161
                VALUES (
1162
                :method, :chat_id, :inline_message_id, :created_at
1163
                );
1164
            ');
1165
1166
            $created_at = self::getTimestamp();
1167
1168
            $sth->bindParam(':chat_id', $chat_id, \PDO::PARAM_STR);
1169
            $sth->bindParam(':inline_message_id', $inline_message_id, \PDO::PARAM_STR);
1170
            $sth->bindParam(':method', $method, \PDO::PARAM_STR);
1171
            $sth->bindParam(':created_at', $created_at, \PDO::PARAM_STR);
1172
1173
            return $sth->execute();
1174
        } catch (\Exception $e) {
1175
            throw new TelegramException($e->getMessage());
1176
        }
1177
    }
1178
}
1179