Passed
Pull Request — develop (#1374)
by
unknown
13:58 queued 03:59
created

Message::getFullCommand()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 3
nop 0
dl 0
loc 12
ccs 7
cts 7
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of the TelegramBot package.
5
 *
6
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Longman\TelegramBot\Entities;
13
14
use Longman\TelegramBot\Entities\Games\Game;
15
use Longman\TelegramBot\Entities\Payments\Invoice;
16
use Longman\TelegramBot\Entities\Payments\SuccessfulPayment;
17
use Longman\TelegramBot\Entities\TelegramPassport\PassportData;
18
use Longman\TelegramBot\Entities\Topics\ForumTopicClosed;
19
use Longman\TelegramBot\Entities\Topics\ForumTopicCreated;
20
use Longman\TelegramBot\Entities\Topics\ForumTopicReopened;
21
22
/**
23
 * Class Message
24
 *
25
 * Represents a message
26
 *
27
 * @link https://core.telegram.org/bots/api#message
28
 *
29
 * @method int                                    getMessageId()                              Unique message identifier
30
 * @method int                                    getMessageThreadId()                        Optional. Unique identifier of a message thread to which the message belongs; for supergroups only
31
 * @method User                                   getFrom()                                   Optional. Sender, can be empty for messages sent to channels
32
 * @method Chat                                   getSenderChat()                             Optional. Sender of the message, sent on behalf of a chat. The channel itself for channel messages. The supergroup itself for messages from anonymous group administrators. The linked channel for messages automatically forwarded to the discussion group
33
 * @method int                                    getDate()                                   Date the message was sent in Unix time
34
 * @method Chat                                   getChat()                                   Conversation the message belongs to
35
 * @method User                                   getForwardFrom()                            Optional. For forwarded messages, sender of the original message
36
 * @method Chat                                   getForwardFromChat()                        Optional. For messages forwarded from a channel, information about the original channel
37
 * @method int                                    getForwardFromMessageId()                   Optional. For forwarded channel posts, identifier of the original message in the channel
38
 * @method string                                 getForwardSignature()                       Optional. For messages forwarded from channels, signature of the post author if present
39
 * @method string                                 getForwardSenderName()                      Optional. Sender's name for messages forwarded from users who disallow adding a link to their account in forwarded messages
40
 * @method int                                    getForwardDate()                            Optional. For forwarded messages, date the original message was sent in Unix time
41
 * @method bool                                   getIsTopicMessage()                         Optional. True, if the message is sent to a forum topic
42
 * @method bool                                   getIsAutomaticForward()                     Optional. True, if the message is a channel post that was automatically forwarded to the connected discussion group
43
 * @method ReplyToMessage                         getReplyToMessage()                         Optional. For replies, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply.
44
 * @method User                                   getViaBot()                                 Optional. Bot through which the message was sent
45
 * @method int                                    getEditDate()                               Optional. Date the message was last edited in Unix time
46
 * @method bool                                   getHasProtectedContent()                    Optional. True, if the message can't be forwarded
47
 * @method string                                 getMediaGroupId()                           Optional. The unique identifier of a media message group this message belongs to
48
 * @method string                                 getAuthorSignature()                        Optional. Signature of the post author for messages in channels
49
 * @method MessageEntity[]                        getEntities()                               Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text
50
 * @method MessageEntity[]                        getCaptionEntities()                        Optional. For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption
51
 * @method Audio                                  getAudio()                                  Optional. Message is an audio file, information about the file
52
 * @method Document                               getDocument()                               Optional. Message is a general file, information about the file
53
 * @method Animation                              getAnimation()                              Optional. Message is an animation, information about the animation. For backward compatibility, when this field is set, the document field will also be set
54
 * @method Game                                   getGame()                                   Optional. Message is a game, information about the game.
55
 * @method PhotoSize[]                            getPhoto()                                  Optional. Message is a photo, available sizes of the photo
56
 * @method Sticker                                getSticker()                                Optional. Message is a sticker, information about the sticker
57
 * @method Video                                  getVideo()                                  Optional. Message is a video, information about the video
58
 * @method Voice                                  getVoice()                                  Optional. Message is a voice message, information about the file
59
 * @method VideoNote                              getVideoNote()                              Optional. Message is a video note message, information about the video
60
 * @method string                                 getCaption()                                Optional. Caption for the document, photo or video, 0-200 characters
61
 * @method Contact                                getContact()                                Optional. Message is a shared contact, information about the contact
62
 * @method Location                               getLocation()                               Optional. Message is a shared location, information about the location
63
 * @method Venue                                  getVenue()                                  Optional. Message is a venue, information about the venue
64
 * @method Poll                                   getPoll()                                   Optional. Message is a native poll, information about the poll
65
 * @method Dice                                   getDice()                                   Optional. Message is a dice with random value, 1-6 for “🎲” and “🎯” base emoji, 1-5 for “🏀” and “⚽” base emoji, 1-64 for “🎰” base emoji
66
 * @method User[]                                 getNewChatMembers()                         Optional. A new member(s) was added to the group, information about them (one of this members may be the bot itself)
67
 * @method User                                   getLeftChatMember()                         Optional. A member was removed from the group, information about them (this member may be the bot itself)
68
 * @method string                                 getNewChatTitle()                           Optional. A chat title was changed to this value
69
 * @method PhotoSize[]                            getNewChatPhoto()                           Optional. A chat photo was changed to this value
70
 * @method MessageAutoDeleteTimerChanged          getMessageAutoDeleteTimerChanged()          Optional. Service message: auto-delete timer settings changed in the chat
71
 * @method bool                                   getDeleteChatPhoto()                        Optional. Service message: the chat photo was deleted
72
 * @method bool                                   getGroupChatCreated()                       Optional. Service message: the group has been created
73
 * @method bool                                   getSupergroupChatCreated()                  Optional. Service message: the supergroup has been created. This field can't be received in a message coming through updates, because bot can’t be a member of a supergroup when it is created. It can only be found in reply_to_message if someone replies to a very first message in a directly created supergroup.
74
 * @method bool                                   getChannelChatCreated()                     Optional. Service message: the channel has been created. This field can't be received in a message coming through updates, because bot can’t be a member of a channel when it is created. It can only be found in reply_to_message if someone replies to a very first message in a channel.
75
 * @method int                                    getMigrateToChatId()                        Optional. The group has been migrated to a supergroup with the specified identifier. This number may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier.
76
 * @method int                                    getMigrateFromChatId()                      Optional. The supergroup has been migrated from a group with the specified identifier. This number may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier.
77
 * @method Message                                getPinnedMessage()                          Optional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply.
78
 * @method Invoice                                getInvoice()                                Optional. Message is an invoice for a payment, information about the invoice.
79
 * @method SuccessfulPayment                      getSuccessfulPayment()                      Optional. Message is a service message about a successful payment, information about the payment.
80
 * @method string                                 getConnectedWebsite()                       Optional. The domain name of the website on which the user has logged in.
81
 * @method PassportData                           getPassportData()                           Optional. Telegram Passport data
82
 * @method ProximityAlertTriggered                getProximityAlertTriggered()                Optional. Service message. A user in the chat triggered another user's proximity alert while sharing Live Location.
83
 * @method ForumTopicCreated                      getForumTopicCreated()                      Optional. Service message: forum topic created
84
 * @method ForumTopicClosed                       getForumTopicClosed()                       Optional. Service message: forum topic closed
85
 * @method ForumTopicReopened                     getForumTopicReopened()                     Optional. Service message: forum topic reopened
86
 * @method VideoChatScheduled                     getVideoChatScheduled()                     Optional. Service message: voice chat scheduled
87
 * @method VideoChatStarted                       getVideoChatStarted()                       Optional. Service message: voice chat started
88
 * @method VideoChatEnded                         getVideoChatEnded()                         Optional. Service message: voice chat ended
89
 * @method VideoChatParticipantsInvited           getVideoChatParticipantsInvited()           Optional. Service message: new participants invited to a voice chat
90
 * @method WebAppData                             getWebAppData()                             Optional. Service message: data sent by a Web App
91
 * @method InlineKeyboard                         getReplyMarkup()                            Optional. Inline keyboard attached to the message. login_url buttons are represented as ordinary url buttons.
92
 */
93
class Message extends Entity
94
{
95
    /**
96
     * {@inheritdoc}
97
     */
98 11
    protected function subEntities(): array
99
    {
100
        return [
101 11
            'from'                              => User::class,
102
            'sender_chat'                       => Chat::class,
103
            'chat'                              => Chat::class,
104
            'forward_from'                      => User::class,
105
            'forward_from_chat'                 => Chat::class,
106
            'reply_to_message'                  => ReplyToMessage::class,
107
            'via_bot'                           => User::class,
108
            'entities'                          => [MessageEntity::class],
109
            'caption_entities'                  => [MessageEntity::class],
110
            'audio'                             => Audio::class,
111
            'document'                          => Document::class,
112
            'animation'                         => Animation::class,
113
            'game'                              => Game::class,
114
            'photo'                             => [PhotoSize::class],
115
            'sticker'                           => Sticker::class,
116
            'video'                             => Video::class,
117
            'voice'                             => Voice::class,
118
            'video_note'                        => VideoNote::class,
119
            'contact'                           => Contact::class,
120
            'location'                          => Location::class,
121
            'venue'                             => Venue::class,
122
            'poll'                              => Poll::class,
123
            'dice'                              => Dice::class,
124
            'new_chat_members'                  => [User::class],
125
            'left_chat_member'                  => User::class,
126
            'new_chat_photo'                    => [PhotoSize::class],
127
            'message_auto_delete_timer_changed' => MessageAutoDeleteTimerChanged::class,
128
            'pinned_message'                    => __CLASS__,
129
            'invoice'                           => Invoice::class,
130
            'successful_payment'                => SuccessfulPayment::class,
131
            'passport_data'                     => PassportData::class,
132
            'proximity_alert_triggered'         => ProximityAlertTriggered::class,
133
            'forum_topic_created'               => ForumTopicCreated::class,
134
            'forum_topic_closed'                => ForumTopicClosed::class,
135
            'forum_topic_reopened'              => ForumTopicReopened::class,
136
            'video_chat_scheduled'              => VideoChatScheduled::class,
137
            'video_chat_started'                => VideoChatStarted::class,
138
            'video_chat_ended'                  => VideoChatEnded::class,
139
            'video_chat_participants_invited'   => VideoChatParticipantsInvited::class,
140
            'web_app_data'                      => WebAppData::class,
141
            'reply_markup'                      => InlineKeyboard::class,
142
        ];
143
    }
144
145
    /**
146
     * return the entire command like /echo or /echo@bot1 if specified
147
     *
148
     * @return string|null
149
     */
150 2
    public function getFullCommand(): ?string
151
    {
152 2
        $text = $this->getProperty('text') ?? '';
153 2
        if (strpos($text, '/') !== 0) {
154 2
            return null;
155
        }
156
157 2
        $no_EOL = strtok($text, PHP_EOL);
158 2
        $no_space = strtok($text, ' ');
159
160
        //try to understand which separator \n or space divide /command from text
161 2
        return strlen($no_space) < strlen($no_EOL) ? $no_space : $no_EOL;
162
    }
163
164
    /**
165
     * Get command
166
     *
167
     * @return string|null
168
     */
169 2
    public function getCommand(): ?string
170
    {
171 2
        if ($command = $this->getProperty('command')) {
172
            return $command;
173
        }
174
175 2
        $full_command = $this->getFullCommand() ?? '';
176 2
        if (strpos($full_command, '/') !== 0) {
177 2
            return null;
178
        }
179 2
        $full_command = substr($full_command, 1);
180
181
        //check if command is followed by bot username
182 2
        $split_cmd = explode('@', $full_command);
183 2
        if (! isset($split_cmd[1])) {
184
            //command is not followed by name
185 2
            return $full_command;
186
        }
187
188 1
        if (strtolower($split_cmd[1]) === strtolower($this->getBotUsername())) {
189
            //command is addressed to me
190 1
            return $split_cmd[0];
191
        }
192
193
        return null;
194
    }
195
196
    /**
197
     * For text messages, the actual UTF-8 text of the message, 0-4096 characters.
198
     *
199
     * @param  bool  $without_cmd
200
     *
201
     * @return string|null
202
     */
203 9
    public function getText($without_cmd = false): ?string
204
    {
205 9
        $text = $this->getProperty('text');
206
207 9
        if ($without_cmd && $command = $this->getFullCommand()) {
208 1
            if (strlen($command) + 1 < strlen($text)) {
0 ignored issues
show
Bug introduced by
It seems like $text can also be of type null; however, parameter $string of strlen() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

208
            if (strlen($command) + 1 < strlen(/** @scrutinizer ignore-type */ $text)) {
Loading history...
209 1
                return substr($text, strlen($command) + 1);
0 ignored issues
show
Bug introduced by
It seems like $text can also be of type null; however, parameter $string of substr() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

209
                return substr(/** @scrutinizer ignore-type */ $text, strlen($command) + 1);
Loading history...
210
            }
211
212 1
            return '';
213
        }
214
215 9
        return $text;
216
    }
217
218
    /**
219
     * Bot added in chat
220
     *
221
     * @return bool
222
     */
223
    public function botAddedInChat(): bool
224
    {
225
        foreach ($this->getNewChatMembers() as $member) {
0 ignored issues
show
Bug introduced by
The method getNewChatMembers() does not exist on Longman\TelegramBot\Entities\Message. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

225
        foreach ($this->/** @scrutinizer ignore-call */ getNewChatMembers() as $member) {
Loading history...
226
            if ($member instanceof User && $member->getUsername() === $this->getBotUsername()) {
227
                return true;
228
            }
229
        }
230
231
        return false;
232
    }
233
234
    /**
235
     * Detect type based on properties.
236
     *
237
     * @return string
238
     */
239 1
    public function getType(): string
240
    {
241
        $types = [
242
            'text',
243
            'audio',
244
            'animation',
245
            'document',
246
            'game',
247
            'photo',
248
            'sticker',
249
            'video',
250
            'voice',
251
            'video_note',
252
            'contact',
253
            'location',
254
            'venue',
255
            'poll',
256
            'dice',
257
            'new_chat_members',
258
            'left_chat_member',
259
            'new_chat_title',
260
            'new_chat_photo',
261
            'delete_chat_photo',
262
            'group_chat_created',
263
            'supergroup_chat_created',
264
            'channel_chat_created',
265
            'message_auto_delete_timer_changed',
266
            'migrate_to_chat_id',
267
            'migrate_from_chat_id',
268
            'pinned_message',
269
            'invoice',
270
            'successful_payment',
271
            'passport_data',
272
            'proximity_alert_triggered',
273
            'forum_topic_created',
274
            'forum_topic_closed',
275
            'forum_topic_reopened',
276
            'video_chat_scheduled',
277
            'video_chat_started',
278
            'video_chat_ended',
279
            'video_chat_participants_invited',
280 1
            'web_app_data',
281 1
            'reply_markup',
282 1
        ];
283 1
284 1
        $is_command = $this->getCommand() !== null;
285
        foreach ($types as $type) {
286
            if ($this->getProperty($type) !== null) {
287 1
                if ($is_command && $type === 'text') {
288
                    return 'command';
289
                }
290
291 1
                return $type;
292
            }
293
        }
294
295
        return 'message';
296
    }
297
}
298