Passed
Push — master ( 627c19...f3fe5e )
by Armando
03:09
created

Message::getText()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 6
nc 3
nop 1
dl 0
loc 13
ccs 7
cts 7
cp 1
crap 4
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
19
/**
20
 * Class Message
21
 *
22
 * Represents a message
23
 *
24
 * @link https://core.telegram.org/bots/api#message
25
 *
26
 * @method int                                    getMessageId()                              Unique message identifier
27
 * @method User                                   getFrom()                                   Optional. Sender, can be empty for messages sent to channels
28
 * @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
29
 * @method int                                    getDate()                                   Date the message was sent in Unix time
30
 * @method Chat                                   getChat()                                   Conversation the message belongs to
31
 * @method User                                   getForwardFrom()                            Optional. For forwarded messages, sender of the original message
32
 * @method Chat                                   getForwardFromChat()                        Optional. For messages forwarded from a channel, information about the original channel
33
 * @method int                                    getForwardFromMessageId()                   Optional. For forwarded channel posts, identifier of the original message in the channel
34
 * @method string                                 getForwardSignature()                       Optional. For messages forwarded from channels, signature of the post author if present
35
 * @method string                                 getForwardSenderName()                      Optional. Sender's name for messages forwarded from users who disallow adding a link to their account in forwarded messages
36
 * @method int                                    getForwardDate()                            Optional. For forwarded messages, date the original message was sent in Unix time
37
 * @method bool                                   getIsAutomaticForward()                     Optional. True, if the message is a channel post that was automatically forwarded to the connected discussion group
38
 * @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.
39
 * @method User                                   getViaBot()                                 Optional. Bot through which the message was sent
40
 * @method int                                    getEditDate()                               Optional. Date the message was last edited in Unix time
41
 * @method bool                                   getHasProtectedContent()                    Optional. True, if the message can't be forwarded
42
 * @method string                                 getMediaGroupId()                           Optional. The unique identifier of a media message group this message belongs to
43
 * @method string                                 getAuthorSignature()                        Optional. Signature of the post author for messages in channels
44
 * @method MessageEntity[]                        getEntities()                               Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text
45
 * @method MessageEntity[]                        getCaptionEntities()                        Optional. For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption
46
 * @method Audio                                  getAudio()                                  Optional. Message is an audio file, information about the file
47
 * @method Document                               getDocument()                               Optional. Message is a general file, information about the file
48
 * @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
49
 * @method Game                                   getGame()                                   Optional. Message is a game, information about the game.
50
 * @method PhotoSize[]                            getPhoto()                                  Optional. Message is a photo, available sizes of the photo
51
 * @method Sticker                                getSticker()                                Optional. Message is a sticker, information about the sticker
52
 * @method Video                                  getVideo()                                  Optional. Message is a video, information about the video
53
 * @method Voice                                  getVoice()                                  Optional. Message is a voice message, information about the file
54
 * @method VideoNote                              getVideoNote()                              Optional. Message is a video note message, information about the video
55
 * @method string                                 getCaption()                                Optional. Caption for the document, photo or video, 0-200 characters
56
 * @method Contact                                getContact()                                Optional. Message is a shared contact, information about the contact
57
 * @method Location                               getLocation()                               Optional. Message is a shared location, information about the location
58
 * @method Venue                                  getVenue()                                  Optional. Message is a venue, information about the venue
59
 * @method Poll                                   getPoll()                                   Optional. Message is a native poll, information about the poll
60
 * @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
61
 * @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)
62
 * @method User                                   getLeftChatMember()                         Optional. A member was removed from the group, information about them (this member may be the bot itself)
63
 * @method string                                 getNewChatTitle()                           Optional. A chat title was changed to this value
64
 * @method PhotoSize[]                            getNewChatPhoto()                           Optional. A chat photo was changed to this value
65
 * @method MessageAutoDeleteTimerChanged          getMessageAutoDeleteTimerChanged()          Optional. Service message: auto-delete timer settings changed in the chat
66
 * @method bool                                   getDeleteChatPhoto()                        Optional. Service message: the chat photo was deleted
67
 * @method bool                                   getGroupChatCreated()                       Optional. Service message: the group has been created
68
 * @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.
69
 * @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.
70
 * @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.
71
 * @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.
72
 * @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.
73
 * @method Invoice                                getInvoice()                                Optional. Message is an invoice for a payment, information about the invoice.
74
 * @method SuccessfulPayment                      getSuccessfulPayment()                      Optional. Message is a service message about a successful payment, information about the payment.
75
 * @method string                                 getConnectedWebsite()                       Optional. The domain name of the website on which the user has logged in.
76
 * @method PassportData                           getPassportData()                           Optional. Telegram Passport data
77
 * @method ProximityAlertTriggered                getProximityAlertTriggered()                Optional. Service message. A user in the chat triggered another user's proximity alert while sharing Live Location.
78
 * @method VideoChatScheduled                     getVideoChatScheduled()                     Optional. Service message: voice chat scheduled
79
 * @method VideoChatStarted                       getVideoChatStarted()                       Optional. Service message: voice chat started
80
 * @method VideoChatEnded                         getVideoChatEnded()                         Optional. Service message: voice chat ended
81
 * @method VideoChatParticipantsInvited           getVideoChatParticipantsInvited()           Optional. Service message: new participants invited to a voice chat
82
 * @method WebAppData                             getWebAppData()                             Optional. Service message: data sent by a Web App
83
 * @method InlineKeyboard                         getReplyMarkup()                            Optional. Inline keyboard attached to the message. login_url buttons are represented as ordinary url buttons.
84
 */
85
class Message extends Entity
86
{
87
    /**
88
     * {@inheritdoc}
89
     */
90 11
    protected function subEntities(): array
91
    {
92
        return [
93 11
            'from'                              => User::class,
94
            'sender_chat'                       => Chat::class,
95
            'chat'                              => Chat::class,
96
            'forward_from'                      => User::class,
97
            'forward_from_chat'                 => Chat::class,
98
            'reply_to_message'                  => ReplyToMessage::class,
99
            'via_bot'                           => User::class,
100
            'entities'                          => [MessageEntity::class],
101
            'caption_entities'                  => [MessageEntity::class],
102
            'audio'                             => Audio::class,
103
            'document'                          => Document::class,
104
            'animation'                         => Animation::class,
105
            'game'                              => Game::class,
106
            'photo'                             => [PhotoSize::class],
107
            'sticker'                           => Sticker::class,
108
            'video'                             => Video::class,
109
            'voice'                             => Voice::class,
110
            'video_note'                        => VideoNote::class,
111
            'contact'                           => Contact::class,
112
            'location'                          => Location::class,
113
            'venue'                             => Venue::class,
114
            'poll'                              => Poll::class,
115
            'dice'                              => Dice::class,
116
            'new_chat_members'                  => [User::class],
117
            'left_chat_member'                  => User::class,
118
            'new_chat_photo'                    => [PhotoSize::class],
119
            'message_auto_delete_timer_changed' => MessageAutoDeleteTimerChanged::class,
120
            'pinned_message'                    => __CLASS__,
121
            'invoice'                           => Invoice::class,
122
            'successful_payment'                => SuccessfulPayment::class,
123
            'passport_data'                     => PassportData::class,
124
            'proximity_alert_triggered'         => ProximityAlertTriggered::class,
125
            'voice_chat_scheduled'              => VoiceChatScheduled::class,           // deprecated
126
            'voice_chat_started'                => VoiceChatStarted::class,             // deprecated
127
            'voice_chat_ended'                  => VoiceChatEnded::class,               // deprecated
128
            'voice_chat_participants_invited'   => VoiceChatParticipantsInvited::class, // deprecated
129
            'video_chat_scheduled'              => VideoChatScheduled::class,
130
            'video_chat_started'                => VideoChatStarted::class,
131
            'video_chat_ended'                  => VideoChatEnded::class,
132
            'video_chat_participants_invited'   => VideoChatParticipantsInvited::class,
133
            'web_app_data'                      => WebAppData::class,
134
            'reply_markup'                      => InlineKeyboard::class,
135
        ];
136
    }
137
138
    /**
139
     * return the entire command like /echo or /echo@bot1 if specified
140
     *
141
     * @return string|null
142
     */
143 2
    public function getFullCommand(): ?string
144
    {
145 2
        $text = $this->getProperty('text') ?? '';
146 2
        if (strpos($text, '/') !== 0) {
147 2
            return null;
148
        }
149
150 2
        $no_EOL = strtok($text, PHP_EOL);
151 2
        $no_space = strtok($text, ' ');
152
153
        //try to understand which separator \n or space divide /command from text
154 2
        return strlen($no_space) < strlen($no_EOL) ? $no_space : $no_EOL;
155
    }
156
157
    /**
158
     * Get command
159
     *
160
     * @return string|null
161
     */
162 2
    public function getCommand(): ?string
163
    {
164 2
        if ($command = $this->getProperty('command')) {
165
            return $command;
166
        }
167
168 2
        $full_command = $this->getFullCommand() ?? '';
169 2
        if (strpos($full_command, '/') !== 0) {
170 2
            return null;
171
        }
172 2
        $full_command = substr($full_command, 1);
173
174
        //check if command is followed by bot username
175 2
        $split_cmd = explode('@', $full_command);
176 2
        if (! isset($split_cmd[1])) {
177
            //command is not followed by name
178 2
            return $full_command;
179
        }
180
181 1
        if (strtolower($split_cmd[1]) === strtolower($this->getBotUsername())) {
182
            //command is addressed to me
183 1
            return $split_cmd[0];
184
        }
185
186
        return null;
187
    }
188
189
    /**
190
     * For text messages, the actual UTF-8 text of the message, 0-4096 characters.
191
     *
192
     * @param  bool  $without_cmd
193
     *
194
     * @return string|null
195
     */
196 9
    public function getText($without_cmd = false): ?string
197
    {
198 9
        $text = $this->getProperty('text');
199
200 9
        if ($without_cmd && $command = $this->getFullCommand()) {
201 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

201
            if (strlen($command) + 1 < strlen(/** @scrutinizer ignore-type */ $text)) {
Loading history...
202 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

202
                return substr(/** @scrutinizer ignore-type */ $text, strlen($command) + 1);
Loading history...
203
            }
204
205 1
            return '';
206
        }
207
208 9
        return $text;
209
    }
210
211
    /**
212
     * Bot added in chat
213
     *
214
     * @return bool
215
     */
216
    public function botAddedInChat(): bool
217
    {
218
        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

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