SendtochannelCommand::execute()   F
last analyzed

Complexity

Conditions 36
Paths 984

Size

Total Lines 188
Code Lines 122

Duplication

Lines 34
Ratio 18.09 %

Code Coverage

Tests 0
CRAP Score 1332

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 34
loc 188
ccs 0
cts 150
cp 0
rs 2.0567
cc 36
eloc 122
nc 984
nop 0
crap 1332

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * This file is part of the TelegramBot package.
4
 *
5
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Longman\TelegramBot\Commands\AdminCommands;
12
13
use Longman\TelegramBot\Entities\Keyboard;
14
use Longman\TelegramBot\Request;
15
use Longman\TelegramBot\Conversation;
16
use Longman\TelegramBot\Commands\AdminCommand;
17
use Longman\TelegramBot\Entities\Message;
18
use Longman\TelegramBot\Exception\TelegramException;
19
20
class SendtochannelCommand extends AdminCommand
21
{
22
    /**
23
     * @var string
24
     */
25
    protected $name = 'sendtochannel';
26
27
    /**
28
     * @var string
29
     */
30
    protected $description = 'Send message to a channel';
31
32
    /**
33
     * @var string
34
     */
35
    protected $usage = '/sendtochannel <message to send>';
36
37
    /**
38
     * @var string
39
     */
40
    protected $version = '0.2.0';
41
42
    /**
43
     * @var bool
44
     */
45
    protected $need_mysql = true;
46
47
    /**
48
     * Conversation Object
49
     *
50
     * @var \Longman\TelegramBot\Conversation
51
     */
52
    protected $conversation;
53
54
    /**
55
     * Command execute method
56
     *
57
     * @return \Longman\TelegramBot\Entities\ServerResponse|mixed
58
     * @throws \Longman\TelegramBot\Exception\TelegramException
59
     */
60
    public function execute()
61
    {
62
        $message = $this->getMessage();
63
        $chat_id = $message->getChat()->getId();
64
        $user_id = $message->getFrom()->getId();
65
66
        $type = $message->getType();
67
        // 'Cast' the command type into message to protect the machine state
68
        // if the commmad is recalled when the conversation is already started
69
        in_array($type, ['command', 'text'], true) && $type = 'message';
70
71
        $text           = trim($message->getText(true));
72
        $text_yes_or_no = ($text === 'Yes' || $text === 'No');
73
74
        $data = [
75
            'chat_id' => $chat_id,
76
        ];
77
78
        // Conversation
79
        $this->conversation = new Conversation($user_id, $chat_id, $this->getName());
80
81
        $notes = &$this->conversation->notes;
82
        !is_array($notes) && $notes = [];
83
84
        $channels = (array) $this->getConfig('your_channel');
85
        if (isset($notes['state'])) {
86
            $state = $notes['state'];
87
        } else {
88
            $state                    = (count($channels) === 0) ? -1 : 0;
89
            $notes['last_message_id'] = $message->getMessageId();
90
        }
91
92
        switch ($state) {
93
            case -1:
94
                // getConfig has not been configured asking for channel to administer
95 View Code Duplication
                if ($type !== 'message' || $text === '') {
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...
96
                    $notes['state'] = -1;
97
                    $this->conversation->update();
98
99
                    $data['text']         = 'Insert the channel name: (@yourchannel)';
100
                    $data['reply_markup'] = Keyboard::remove(['selective' => true]);
101
                    $result               = Request::sendMessage($data);
102
103
                    break;
104
                }
105
                $notes['channel']         = $text;
106
                $notes['last_message_id'] = $message->getMessageId();
107
                // Jump to state 1
108
                goto insert;
109
110
            // no break
111
            default:
112
            case 0:
0 ignored issues
show
Unused Code introduced by
case 0: // getConfig...essage->getMessageId(); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
113
                // getConfig has been configured choose channel
114
                if ($type !== 'message' || !in_array($text, $channels, true)) {
115
                    $notes['state'] = 0;
116
                    $this->conversation->update();
117
118
                    $keyboard = [];
119
                    foreach ($channels as $channel) {
120
                        $keyboard[] = [$channel];
121
                    }
122
                    $data['reply_markup'] = new Keyboard(
123
                        [
124
                            'keyboard'          => $keyboard,
125
                            'resize_keyboard'   => true,
126
                            'one_time_keyboard' => true,
127
                            'selective'         => true,
128
                        ]
129
                    );
130
131
                    $data['text'] = 'Select a channel from the keyboard:';
132
                    $result       = Request::sendMessage($data);
133
                    break;
134
                }
135
                $notes['channel']         = $text;
136
                $notes['last_message_id'] = $message->getMessageId();
137
138
            // no break
139
            case 1:
140
                insert:
141 View Code Duplication
                if (($type === 'message' && $text === '') || $notes['last_message_id'] === $message->getMessageId()) {
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...
142
                    $notes['state'] = 1;
143
                    $this->conversation->update();
144
145
                    $data['reply_markup'] = Keyboard::remove(['selective' => true]);
146
                    $data['text']         = 'Insert the content you want to share: text, photo, audio...';
147
                    $result               = Request::sendMessage($data);
148
                    break;
149
                }
150
                $notes['last_message_id'] = $message->getMessageId();
151
                $notes['message']         = $message->getRawData();
152
                $notes['message_type']    = $type;
153
            // no break
154
            case 2:
155
                if (!$text_yes_or_no || $notes['last_message_id'] === $message->getMessageId()) {
156
                    $notes['state'] = 2;
157
                    $this->conversation->update();
158
159
                    // Execute this just with object that allow caption
160
                    if (in_array($notes['message_type'], ['video', 'photo'], true)) {
161
                        $data['reply_markup'] = new Keyboard(
162
                            [
163
                                'keyboard'          => [['Yes', 'No']],
164
                                'resize_keyboard'   => true,
165
                                'one_time_keyboard' => true,
166
                                'selective'         => true,
167
                            ]
168
                        );
169
170
                        $data['text'] = 'Would you like to insert a caption?';
171 View Code Duplication
                        if (!$text_yes_or_no && $notes['last_message_id'] !== $message->getMessageId()) {
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...
172
                            $data['text'] .= PHP_EOL . 'Type Yes or No';
173
                        }
174
                        $result = Request::sendMessage($data);
175
                        break;
176
                    }
177
                }
178
                $notes['set_caption']     = ($text === 'Yes');
179
                $notes['last_message_id'] = $message->getMessageId();
180
            // no break
181
            case 3:
182 View Code Duplication
                if ($notes['set_caption'] && ($notes['last_message_id'] === $message->getMessageId() || $type !== '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...
183
                    $notes['state'] = 3;
184
                    $this->conversation->update();
185
186
                    $data['text']         = 'Insert caption:';
187
                    $data['reply_markup'] = Keyboard::remove(['selective' => true]);
188
                    $result               = Request::sendMessage($data);
189
                    break;
190
                }
191
                $notes['last_message_id'] = $message->getMessageId();
192
                $notes['caption']         = $text;
193
            // no break
194
            case 4:
195
                if (!$text_yes_or_no || $notes['last_message_id'] === $message->getMessageId()) {
196
                    $notes['state'] = 4;
197
                    $this->conversation->update();
198
199
                    $data['text'] = 'Message will look like this:';
200
                    $result       = Request::sendMessage($data);
201
202
                    if ($notes['message_type'] !== 'command') {
203
                        if ($notes['set_caption']) {
204
                            $data['caption'] = $notes['caption'];
205
                        }
206
                        $this->sendBack(new Message($notes['message'], $this->telegram->getBotName()), $data);
207
208
                        $data['reply_markup'] = new Keyboard(
209
                            [
210
                                'keyboard'          => [['Yes', 'No']],
211
                                'resize_keyboard'   => true,
212
                                'one_time_keyboard' => true,
213
                                'selective'         => true,
214
                            ]
215
                        );
216
217
                        $data['text'] = 'Would you like to post it?';
218 View Code Duplication
                        if (!$text_yes_or_no && $notes['last_message_id'] !== $message->getMessageId()) {
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...
219
                            $data['text'] .= PHP_EOL . 'Type Yes or No';
220
                        }
221
                        $result = Request::sendMessage($data);
222
                    }
223
                    break;
224
                }
225
226
                $notes['post_message']    = ($text === 'Yes');
227
                $notes['last_message_id'] = $message->getMessageId();
228
            // no break
229
            case 5:
230
                $data['reply_markup'] = Keyboard::remove(['selective' => true]);
231
232
                if ($notes['post_message']) {
233
                    $data['text'] = $this->publish(
234
                        new Message($notes['message'], $this->telegram->getBotName()),
235
                        $notes['channel'],
236
                        $notes['caption']
237
                    );
238
                } else {
239
                    $data['text'] = 'Abort by user, message not sent..';
240
                }
241
242
                $this->conversation->stop();
243
                $result = Request::sendMessage($data);
244
        }
245
246
        return $result;
247
    }
248
249
    /**
250
     * SendBack
251
     *
252
     * Received a message, the bot can send a copy of it to another chat/channel.
253
     * You don't have to care about the type of the message, the function detect it and use the proper
254
     * REQUEST:: function to send it.
255
     * $data include all the var that you need to send the message to the proper chat
256
     *
257
     * @todo This method will be moved to a higher level maybe in AdminCommand or Command
258
     * @todo Looking for a more significant name
259
     *
260
     * @param \Longman\TelegramBot\Entities\Message $message
261
     * @param array                                 $data
262
     *
263
     * @return \Longman\TelegramBot\Entities\ServerResponse
264
     * @throws \Longman\TelegramBot\Exception\TelegramException
265
     */
266
    protected function sendBack(Message $message, array $data)
267
    {
268
        $type = $message->getType();
269
        in_array($type, ['command', 'text'], true) && $type = 'message';
270
271
        if ($type === 'message') {
272
            $data['text'] = $message->getText(true);
273
        } elseif ($type === 'audio') {
274
            $data['audio']     = $message->getAudio()->getFileId();
275
            $data['duration']  = $message->getAudio()->getDuration();
276
            $data['performer'] = $message->getAudio()->getPerformer();
277
            $data['title']     = $message->getAudio()->getTitle();
278
        } elseif ($type === 'document') {
279
            $data['document'] = $message->getDocument()->getFileId();
280
        } elseif ($type === 'photo') {
281
            $data['photo'] = $message->getPhoto()[0]->getFileId();
282
        } elseif ($type === 'sticker') {
283
            $data['sticker'] = $message->getSticker()->getFileId();
284
        } elseif ($type === 'video') {
285
            $data['video'] = $message->getVideo()->getFileId();
286
        } elseif ($type === 'voice') {
287
            $data['voice'] = $message->getVoice()->getFileId();
288
        } elseif ($type === 'location') {
289
            $data['latitude']  = $message->getLocation()->getLatitude();
290
            $data['longitude'] = $message->getLocation()->getLongitude();
291
        }
292
293
        $callback_path     = 'Longman\TelegramBot\Request';
294
        $callback_function = 'send' . ucfirst($type);
295
        if (!method_exists($callback_path, $callback_function)) {
296
            throw new TelegramException('Methods: ' . $callback_function . ' not found in class Request.');
297
        }
298
299
        return $callback_path::$callback_function($data);
300
    }
301
302
    /**
303
     * Publish a message to a channel and return success or failure message
304
     *
305
     * @param \Longman\TelegramBot\Entities\Message $message
306
     * @param int                                   $channel
307
     * @param string|null                           $caption
308
     *
309
     * @return string
310
     * @throws \Longman\TelegramBot\Exception\TelegramException
311
     */
312
    protected function publish(Message $message, $channel, $caption = null)
313
    {
314
        $data = [
315
            'chat_id' => $channel,
316
            'caption' => $caption,
317
        ];
318
319
        if ($this->sendBack($message, $data)->isOk()) {
320
            $response = 'Message sent successfully to: ' . $channel;
321
        } else {
322
            $response = 'Message not sent to: ' . $channel . PHP_EOL .
323
                        '- Does the channel exist?' . PHP_EOL .
324
                        '- Is the bot an admin of the channel?';
325
        }
326
327
        return $response;
328
    }
329
330
    /**
331
     * Execute without db
332
     *
333
     * @todo Why send just to the first found channel?
334
     *
335
     * @return mixed
336
     * @throws \Longman\TelegramBot\Exception\TelegramException
337
     */
338
    public function executeNoDb()
339
    {
340
        $message = $this->getMessage();
341
        $chat_id = $message->getChat()->getId();
342
        $text    = trim($message->getText(true));
343
344
        $data = [
345
            'chat_id' => $chat_id,
346
            'text'    => 'Usage: ' . $this->getUsage(),
347
        ];
348
349
        if ($text !== '') {
350
            $channels      = (array) $this->getConfig('your_channel');
351
            $first_channel = $channels[0];
352
            $data['text']  = $this->publish(
353
                new Message($message->getRawData(), $this->telegram->getBotName()),
354
                $first_channel
355
            );
356
        }
357
358
        return Request::sendMessage($data);
359
    }
360
}
361