Completed
Push — feature/improve-code ( e986a1...36787d )
by Avtandil
14:14
created

Request::sendVoice()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 12
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 12
loc 12
rs 9.4285
ccs 0
cts 6
cp 0
cc 3
eloc 6
nc 3
nop 2
crap 12
1
<?php
2
/**
3
 * This file is part of the TelegramBot package.
4
 *
5
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Longman\TelegramBot;
12
13
use GuzzleHttp\Client;
14
use GuzzleHttp\Exception\RequestException;
15
use Longman\TelegramBot\Entities\File;
16
use Longman\TelegramBot\Entities\ServerResponse;
17
use Longman\TelegramBot\Exception\TelegramException;
18
19
class Request
20
{
21
    /**
22
     * Telegram object
23
     *
24
     * @var \Longman\TelegramBot\Telegram
25
     */
26
    private static $telegram;
27
28
    /**
29
     * URI of the Telegram API
30
     *
31
     * @var string
32
     */
33
    private static $api_base_uri = 'https://api.telegram.org';
34
35
    /**
36
     * Guzzle Client object
37
     *
38
     * @var \GuzzleHttp\Client
39
     */
40
    private static $client;
41
42
    /**
43
     * Input value of the request
44
     *
45
     * @var string
46
     */
47
    private static $input;
48
49
    /**
50
     * Available actions to send
51
     *
52
     * @var array
53
     */
54
    private static $actions = [
55
        'getUpdates',
56
        'setWebhook',
57
        'getMe',
58
        'sendMessage',
59
        'forwardMessage',
60
        'sendPhoto',
61
        'sendAudio',
62
        'sendDocument',
63
        'sendSticker',
64
        'sendVideo',
65
        'sendVoice',
66
        'sendLocation',
67
        'sendVenue',
68
        'sendContact',
69
        'sendChatAction',
70
        'getUserProfilePhotos',
71
        'getFile',
72
        'kickChatMember',
73
        'leaveChat',
74
        'unbanChatMember',
75
        'getChat',
76
        'getChatAdministrators',
77
        'getChatMember',
78
        'getChatMembersCount',
79
        'answerCallbackQuery',
80
        'answerInlineQuery',
81
        'editMessageText',
82
        'editMessageCaption',
83
        'editMessageReplyMarkup',
84
    ];
85
86
    /**
87
     * Initialize
88
     *
89
     * @param \Longman\TelegramBot\Telegram $telegram
90
     * @throws \Longman\TelegramBot\Exception\TelegramException
91
     */
92 39
    public static function initialize(Telegram $telegram)
93
    {
94 39
        if (is_object($telegram)) {
95 39
            self::$telegram = $telegram;
96 39
            self::$client   = new Client(['base_uri' => self::$api_base_uri]);
97
        } else {
98
            throw new TelegramException('Telegram pointer is empty!');
99
        }
100 39
    }
101
102
    /**
103
     * Set input from custom input or stdin and return it
104
     *
105
     * @return string
106
     * @throws \Longman\TelegramBot\Exception\TelegramException
107
     */
108
    public static function getInput()
109
    {
110
        // First check if a custom input has been set, else get the PHP input.
111
        if (!($input = self::$telegram->getCustomInput())) {
112
            $input = file_get_contents('php://input');
113
        }
114
115
        // Make sure we have a string to work with.
116
        if (is_string($input)) {
117
            self::$input = $input;
118
        } else {
119
            throw new TelegramException('Input must be a string!');
120
        }
121
122
        TelegramLog::update(self::$input);
123
        return self::$input;
124
    }
125
126
    /**
127
     * Generate general fake server response
128
     *
129
     * @param array $data Data to add to fake response
130
     *
131
     * @return array Fake response data
132
     */
133 6
    public static function generateGeneralFakeServerResponse(array $data = null)
134
    {
135
        //PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php
136
        //Maybe this is not the best possible implementation
137
138
        //No value set in $data ie testing setWebhook
139
        //Provided $data['chat_id'] ie testing sendMessage
140
141 6
        $fake_response = ['ok' => true]; // :)
142
143 6
        if (!isset($data)) {
144 1
            $fake_response['result'] = true;
145
        }
146
147
        //some data to let iniatilize the class method SendMessage
148 6
        if (isset($data['chat_id'])) {
149 6
            $data['message_id'] = '1234';
150 6
            $data['date']       = '1441378360';
151 6
            $data['from']       = [
152
                'id'         => 123456789,
153
                'first_name' => 'botname',
154
                'username'   => 'namebot',
155
            ];
156 6
            $data['chat']       = ['id' => $data['chat_id']];
157
158 6
            $fake_response['result'] = $data;
159
        }
160
161 6
        return $fake_response;
162
    }
163
164
    /**
165
     * Execute HTTP Request
166
     *
167
     * @param string     $action Action to execute
168
     * @param array|null $data   Data to attach to the execution
169
     *
170
     * @return mixed Result of the HTTP Request
171
     * @throws \Longman\TelegramBot\Exception\TelegramException
172
     */
173
    public static function execute($action, array $data = null)
174
    {
175
        $debug_handle = TelegramLog::getDebugLogTempStream();
176
177
        //Fix so that the keyboard markup is a string, not an object
178
        if (isset($data['reply_markup']) && !is_string($data['reply_markup'])) {
179
            $data['reply_markup'] = (string) $data['reply_markup'];
180
        }
181
182
        $request_params = ['debug' => $debug_handle];
183
184
        //Check for resources in data
185
        $contains_resource = false;
186
        foreach ($data as $item) {
187
            if (is_resource($item)) {
188
                $contains_resource = true;
189
                break;
190
            }
191
        }
192
193
        //Reformat data array in multipart way
194
        if ($contains_resource) {
195
            foreach ($data as $key => $item) {
196
                $request_params['multipart'][] = array('name' => $key, 'contents' => $item);
197
            }
198
        } else {
199
            $request_params['form_params'] = $data;
200
        }
201
202
        try {
203
            $response = self::$client->post(
204
                '/bot' . self::$telegram->getApiKey() . '/' . $action,
205
                $request_params
206
            );
207
        } catch (RequestException $e) {
208
            throw new TelegramException($e->getMessage());
209
        } finally {
210
            //Logging verbose debug output
211
            TelegramLog::endDebugLogTempStream("Verbose HTTP Request output:\n%s\n");
212
        }
213
214
        $result = $response->getBody();
215
216
        //Logging getUpdates Update
217
        if ($action === 'getUpdates') {
218
            TelegramLog::update($result);
219
        }
220
221
        return $result;
222
    }
223
224
    /**
225
     * Download file
226
     *
227
     * @param Entities\File $file
228
     *
229
     * @return boolean
230
     * @throws \Longman\TelegramBot\Exception\TelegramException
231
     */
232
    public static function downloadFile(File $file)
233
    {
234
        $path = $file->getFilePath();
235
236
        //Create the directory
237
        $loc_path = self::$telegram->getDownloadPath() . '/' . $path;
238
239
        $dirname = dirname($loc_path);
240
        if (!is_dir($dirname) && !mkdir($dirname, 0755, true)) {
241
            throw new TelegramException('Directory ' . $dirname . ' can\'t be created');
242
        }
243
244
        $debug_handle = TelegramLog::getDebugLogTempStream();
245
246
        try {
247
            $response = self::$client->get(
0 ignored issues
show
Unused Code introduced by
$response is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
248
                '/file/bot' . self::$telegram->getApiKey() . '/' . $path,
249
                ['debug' => $debug_handle, 'sink' => $loc_path]
250
            );
251
        } catch (RequestException $e) {
252
            throw new TelegramException($e->getMessage());
253
        } finally {
254
            //Logging verbose debug output
255
            TelegramLog::endDebugLogTempStream("Verbose HTTP File Download Request output:\n%s\n");
256
        }
257
258
        return (filesize($loc_path) > 0);
259
    }
260
261
    /**
262
     * Encode file
263
     *
264
     * @param string $file
265
     *
266
     * @return resource
267
     * @throws \Longman\TelegramBot\Exception\TelegramException
268
     */
269
    protected static function encodeFile($file)
270
    {
271
        $fp = fopen($file, 'r');
272
        if ($fp === false) {
273
            throw new TelegramException('Cannot open ' . $file . ' for reading');
274
        }
275
        return $fp;
276
    }
277
278
    /**
279
     * Send command
280
     *
281
     * @todo Fake response doesn't need json encoding?
282
     *
283
     * @param string     $action
284
     * @param array|null $data
285
     *
286
     * @return \Longman\TelegramBot\Entities\ServerResponse
287
     * @throws \Longman\TelegramBot\Exception\TelegramException
288
     */
289 5
    public static function send($action, array $data = null)
290
    {
291 5
        if (!in_array($action, self::$actions)) {
292
            throw new TelegramException('The action ' . $action . ' doesn\'t exist!');
293
        }
294
295 5
        $bot_name = self::$telegram->getBotName();
296
297 5
        if (defined('PHPUNIT_TESTSUITE')) {
298 5
            $fake_response = self::generateGeneralFakeServerResponse($data);
299 5
            return new ServerResponse($fake_response, $bot_name);
300
        }
301
302
        $response = json_decode(self::execute($action, $data), true);
303
304
        if (is_null($response)) {
305
            throw new TelegramException('Telegram returned an invalid response! Please your bot name and api token.');
306
        }
307
308
        return new ServerResponse($response, $bot_name);
309
    }
310
311
    /**
312
     * Get me
313
     *
314
     * @return mixed
315
     */
316
    public static function getMe()
317
    {
318
        // Added fake parameter, because of some cURL version failed POST request without parameters
319
        // see https://github.com/akalongman/php-telegram-bot/pull/228
320
        return self::send('getMe', ['whoami']);
321
    }
322
323
    /**
324
     * Send message
325
     *
326
     * @todo Could do with some cleaner recursion
327
     *
328
     * @param array $data
329
     *
330
     * @return mixed
331
     * @throws \Longman\TelegramBot\Exception\TelegramException
332
     */
333 5
    public static function sendMessage(array $data)
334
    {
335 5
        if (empty($data)) {
336
            throw new TelegramException('Data is empty!');
337
        }
338 5
        $text            = $data['text'];
339 5
        $string_len_utf8 = mb_strlen($text, 'UTF-8');
340 5
        if ($string_len_utf8 > 4096) {
341
            $data['text'] = mb_substr($text, 0, 4096);
342
            self::send('sendMessage', $data);
343
            $data['text'] = mb_substr($text, 4096, $string_len_utf8);
344
            return self::sendMessage($data);
345
        }
346 5
        return self::send('sendMessage', $data);
347
    }
348
349
    /**
350
     * Forward message
351
     *
352
     * @param array $data
353
     *
354
     * @return mixed
355
     * @throws \Longman\TelegramBot\Exception\TelegramException
356
     */
357
    public static function forwardMessage(array $data)
358
    {
359
        if (empty($data)) {
360
            throw new TelegramException('Data is empty!');
361
        }
362
363
        return self::send('forwardMessage', $data);
364
    }
365
366
    /**
367
     * Send photo
368
     *
369
     * @param array  $data
370
     * @param string $file
371
     *
372
     * @return mixed
373
     * @throws \Longman\TelegramBot\Exception\TelegramException
374
     */
375 View Code Duplication
    public static function sendPhoto(array $data, $file = null)
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...
376
    {
377
        if (empty($data)) {
378
            throw new TelegramException('Data is empty!');
379
        }
380
381
        if (!is_null($file)) {
382
            $data['photo'] = self::encodeFile($file);
383
        }
384
385
        return self::send('sendPhoto', $data);
386
    }
387
388
    /**
389
     * Send audio
390
     *
391
     * @param array  $data
392
     * @param string $file
393
     *
394
     * @return mixed
395
     * @throws \Longman\TelegramBot\Exception\TelegramException
396
     */
397 View Code Duplication
    public static function sendAudio(array $data, $file = null)
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...
398
    {
399
        if (empty($data)) {
400
            throw new TelegramException('Data is empty!');
401
        }
402
403
        if (!is_null($file)) {
404
            $data['audio'] = self::encodeFile($file);
405
        }
406
407
        return self::send('sendAudio', $data);
408
    }
409
410
    /**
411
     * Send document
412
     *
413
     * @param array  $data
414
     * @param string $file
415
     *
416
     * @return mixed
417
     * @throws \Longman\TelegramBot\Exception\TelegramException
418
     */
419 View Code Duplication
    public static function sendDocument(array $data, $file = null)
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...
420
    {
421
        if (empty($data)) {
422
            throw new TelegramException('Data is empty!');
423
        }
424
425
        if (!is_null($file)) {
426
            $data['document'] = self::encodeFile($file);
427
        }
428
429
        return self::send('sendDocument', $data);
430
    }
431
432
    /**
433
     * Send sticker
434
     *
435
     * @param array  $data
436
     * @param string $file
437
     *
438
     * @return mixed
439
     * @throws \Longman\TelegramBot\Exception\TelegramException
440
     */
441 View Code Duplication
    public static function sendSticker(array $data, $file = null)
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...
442
    {
443
        if (empty($data)) {
444
            throw new TelegramException('Data is empty!');
445
        }
446
447
        if (!is_null($file)) {
448
            $data['sticker'] = self::encodeFile($file);
449
        }
450
451
        return self::send('sendSticker', $data);
452
    }
453
454
    /**
455
     * Send video
456
     *
457
     * @param array  $data
458
     * @param string $file
459
     *
460
     * @return mixed
461
     * @throws \Longman\TelegramBot\Exception\TelegramException
462
     */
463 View Code Duplication
    public static function sendVideo(array $data, $file = null)
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...
464
    {
465
        if (empty($data)) {
466
            throw new TelegramException('Data is empty!');
467
        }
468
469
        if (!is_null($file)) {
470
            $data['video'] = self::encodeFile($file);
471
        }
472
473
        return self::send('sendVideo', $data);
474
    }
475
476
    /**
477
     * Send voice
478
     *
479
     * @param array  $data
480
     * @param string $file
481
     *
482
     * @return mixed
483
     * @throws \Longman\TelegramBot\Exception\TelegramException
484
     */
485 View Code Duplication
    public static function sendVoice(array $data, $file = null)
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...
486
    {
487
        if (empty($data)) {
488
            throw new TelegramException('Data is empty!');
489
        }
490
491
        if (!is_null($file)) {
492
            $data['voice'] = self::encodeFile($file);
493
        }
494
495
        return self::send('sendVoice', $data);
496
    }
497
498
    /**
499
     * Send location
500
     *
501
     * @param array $data
502
     *
503
     * @return mixed
504
     * @throws \Longman\TelegramBot\Exception\TelegramException
505
     */
506
    public static function sendLocation(array $data)
507
    {
508
        if (empty($data)) {
509
            throw new TelegramException('Data is empty!');
510
        }
511
512
        return self::send('sendLocation', $data);
513
    }
514
515
    /**
516
     * Send venue
517
     *
518
     * @param array $data
519
     *
520
     * @return mixed
521
     * @throws \Longman\TelegramBot\Exception\TelegramException
522
     */
523
    public static function sendVenue(array $data)
524
    {
525
        if (empty($data)) {
526
            throw new TelegramException('Data is empty!');
527
        }
528
529
        return self::send('sendVenue', $data);
530
    }
531
532
    /**
533
     * Send contact
534
     *
535
     * @param array $data
536
     *
537
     * @return mixed
538
     * @throws \Longman\TelegramBot\Exception\TelegramException
539
     */
540
    public static function sendContact(array $data)
541
    {
542
        if (empty($data)) {
543
            throw new TelegramException('Data is empty!');
544
        }
545
546
        return self::send('sendContact', $data);
547
    }
548
549
    /**
550
     * Send chat action
551
     *
552
     * @param array $data
553
     *
554
     * @return mixed
555
     * @throws \Longman\TelegramBot\Exception\TelegramException
556
     */
557
    public static function sendChatAction(array $data)
558
    {
559
        if (empty($data)) {
560
            throw new TelegramException('Data is empty!');
561
        }
562
563
        return self::send('sendChatAction', $data);
564
    }
565
566
    /**
567
     * Get user profile photos
568
     *
569
     * @param array $data
570
     *
571
     * @return mixed
572
     * @throws \Longman\TelegramBot\Exception\TelegramException
573
     */
574
    public static function getUserProfilePhotos(array $data)
575
    {
576
        if (empty($data)) {
577
            throw new TelegramException('Data is empty!');
578
        }
579
580
        if (!isset($data['user_id'])) {
581
            throw new TelegramException('User id is empty!');
582
        }
583
584
        return self::send('getUserProfilePhotos', $data);
585
    }
586
587
    /**
588
     * Get updates
589
     *
590
     * @param array $data
591
     *
592
     * @return mixed
593
     */
594
    public static function getUpdates(array $data)
595
    {
596
        return self::send('getUpdates', $data);
597
    }
598
599
    /**
600
     * Set webhook
601
     *
602
     * @param string $url
603
     * @param string $file
604
     *
605
     * @return mixed
606
     */
607
    public static function setWebhook($url = '', $file = null)
608
    {
609
        $data = ['url' => $url];
610
611
        if (!is_null($file)) {
612
            $data['certificate'] = self::encodeFile($file);
613
        }
614
615
        return self::send('setWebhook', $data);
616
    }
617
618
    /**
619
     * Get file
620
     *
621
     * @param array $data
622
     *
623
     * @return mixed
624
     * @throws \Longman\TelegramBot\Exception\TelegramException
625
     */
626
    public static function getFile(array $data)
627
    {
628
        if (empty($data)) {
629
            throw new TelegramException('Data is empty!');
630
        }
631
632
        return self::send('getFile', $data);
633
    }
634
635
    /**
636
     * Kick Chat Member
637
     *
638
     * @param array $data
639
     *
640
     * @return mixed
641
     * @throws \Longman\TelegramBot\Exception\TelegramException
642
     */
643
    public static function kickChatMember(array $data)
644
    {
645
        if (empty($data)) {
646
            throw new TelegramException('Data is empty!');
647
        }
648
649
        return self::send('kickChatMember', $data);
650
    }
651
652
    /**
653
     * Leave Chat
654
     *
655
     * @param array $data
656
     *
657
     * @return mixed
658
     * @throws \Longman\TelegramBot\Exception\TelegramException
659
     */
660
    public static function leaveChat(array $data)
661
    {
662
        if (empty($data)) {
663
            throw new TelegramException('Data is empty!');
664
        }
665
666
        return self::send('leaveChat', $data);
667
    }
668
669
    /**
670
     * Unban Chat Member
671
     *
672
     * @param array $data
673
     *
674
     * @return mixed
675
     * @throws \Longman\TelegramBot\Exception\TelegramException
676
     */
677
    public static function unbanChatMember(array $data)
678
    {
679
        if (empty($data)) {
680
            throw new TelegramException('Data is empty!');
681
        }
682
683
        return self::send('unbanChatMember', $data);
684
    }
685
686
    /**
687
     * Get Chat
688
     *
689
     * @todo add get response in ServerResponse.php?
690
     *
691
     * @param array $data
692
     *
693
     * @return mixed
694
     * @throws \Longman\TelegramBot\Exception\TelegramException
695
     */
696
    public static function getChat(array $data)
697
    {
698
        if (empty($data)) {
699
            throw new TelegramException('Data is empty!');
700
        }
701
702
        return self::send('getChat', $data);
703
    }
704
705
    /**
706
     * Get Chat Administrators
707
     *
708
     * @todo add get response in ServerResponse.php?
709
     *
710
     * @param array $data
711
     *
712
     * @return mixed
713
     * @throws \Longman\TelegramBot\Exception\TelegramException
714
     */
715
    public static function getChatAdministrators(array $data)
716
    {
717
        if (empty($data)) {
718
            throw new TelegramException('Data is empty!');
719
        }
720
721
        return self::send('getChatAdministrators', $data);
722
    }
723
724
    /**
725
     * Get Chat Members Count
726
     *
727
     * @todo add get response in ServerResponse.php?
728
     *
729
     * @param array $data
730
     *
731
     * @return mixed
732
     * @throws \Longman\TelegramBot\Exception\TelegramException
733
     */
734
    public static function getChatMembersCount(array $data)
735
    {
736
        if (empty($data)) {
737
            throw new TelegramException('Data is empty!');
738
        }
739
740
        return self::send('getChatMembersCount', $data);
741
    }
742
743
    /**
744
     * Get Chat Member
745
     *
746
     * @todo add get response in ServerResponse.php?
747
     *
748
     * @param array $data
749
     *
750
     * @return mixed
751
     * @throws \Longman\TelegramBot\Exception\TelegramException
752
     */
753
    public static function getChatMember(array $data)
754
    {
755
        if (empty($data)) {
756
            throw new TelegramException('Data is empty!');
757
        }
758
759
        return self::send('getChatMember', $data);
760
    }
761
762
    /**
763
     * Answer callback query
764
     *
765
     * @param array $data
766
     *
767
     * @return mixed
768
     * @throws \Longman\TelegramBot\Exception\TelegramException
769
     */
770
    public static function answerCallbackQuery(array $data)
771
    {
772
        if (empty($data)) {
773
            throw new TelegramException('Data is empty!');
774
        }
775
776
        return self::send('answerCallbackQuery', $data);
777
    }
778
779
    /**
780
     * Answer inline query
781
     *
782
     * @param array $data
783
     *
784
     * @return mixed
785
     * @throws \Longman\TelegramBot\Exception\TelegramException
786
     */
787
    public static function answerInlineQuery(array $data)
788
    {
789
        if (empty($data)) {
790
            throw new TelegramException('Data is empty!');
791
        }
792
793
        return self::send('answerInlineQuery', $data);
794
    }
795
796
    /**
797
     * Edit message text
798
     *
799
     * @param array $data
800
     *
801
     * @return mixed
802
     * @throws \Longman\TelegramBot\Exception\TelegramException
803
     */
804
    public static function editMessageText(array $data)
805
    {
806
        if (empty($data)) {
807
            throw new TelegramException('Data is empty!');
808
        }
809
810
        return self::send('editMessageText', $data);
811
    }
812
813
    /**
814
     * Edit message caption
815
     *
816
     * @param array $data
817
     *
818
     * @return mixed
819
     * @throws \Longman\TelegramBot\Exception\TelegramException
820
     */
821
    public static function editMessageCaption(array $data)
822
    {
823
        if (empty($data)) {
824
            throw new TelegramException('Data is empty!');
825
        }
826
827
        return self::send('editMessageCaption', $data);
828
    }
829
830
    /**
831
     * Edit message reply markup
832
     *
833
     * @param array $data
834
     *
835
     * @return mixed
836
     * @throws \Longman\TelegramBot\Exception\TelegramException
837
     */
838
    public static function editMessageReplyMarkup(array $data)
839
    {
840
        if (empty($data)) {
841
            throw new TelegramException('Data is empty!');
842
        }
843
844
        return self::send('editMessageReplyMarkup', $data);
845
    }
846
847
    /**
848
     * Return an empty Server Response
849
     *
850
     * No request to telegram are sent, this function is used in commands that
851
     * don't need to fire a message after execution
852
     *
853
     * @return Entities\ServerResponse
854
     */
855
    public static function emptyResponse()
856
    {
857
        return new ServerResponse(['ok' => true, 'result' => true], null);
858
    }
859
860
    /**
861
     * Send message to all active chats
862
     *
863
     * @param string  $callback_function
864
     * @param array   $data
865
     * @param boolean $send_groups
866
     * @param boolean $send_super_groups
867
     * @param boolean $send_users
868
     * @param string  $date_from
869
     * @param string  $date_to
870
     *
871
     * @return array
872
     * @throws \Longman\TelegramBot\Exception\TelegramException
873
     */
874
    public static function sendToActiveChats(
875
        $callback_function,
876
        array $data,
877
        $send_groups = true,
878
        $send_super_groups = true,
879
        $send_users = true,
880
        $date_from = null,
881
        $date_to = null
882
    ) {
883
        $callback_path = __NAMESPACE__ . '\Request';
884
        if (!method_exists($callback_path, $callback_function)) {
885
            throw new TelegramException('Method "' . $callback_function . '" not found in class Request.');
886
        }
887
888
        $chats = DB::selectChats($send_groups, $send_super_groups, $send_users, $date_from, $date_to);
889
890
        $results = [];
891
        foreach ($chats as $row) {
0 ignored issues
show
Bug introduced by
The expression $chats of type false|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
892
            $data['chat_id'] = $row['chat_id'];
893
            $results[]       = call_user_func_array($callback_path . '::' . $callback_function, [$data]);
894
        }
895
896
        return $results;
897
    }
898
}
899