Passed
Push — develop ( ce83ec...1c6380 )
by
unknown
18:21 queued 16:17
created

Message   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 215
Duplicated Lines 0 %

Test Coverage

Coverage 94.93%

Importance

Changes 6
Bugs 1 Features 1
Metric Value
eloc 131
c 6
b 1
f 1
dl 0
loc 215
ccs 131
cts 138
cp 0.9493
rs 10
wmc 22

6 Methods

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

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

225
                return substr(/** @scrutinizer ignore-type */ $text, strlen($command) + 1);
Loading history...
226
            }
227
228 1
            return '';
229
        }
230
231 9
        return $text;
232
    }
233
234
    /**
235
     * Bot added in chat
236
     *
237
     * @return bool
238
     */
239
    public function botAddedInChat(): bool
240
    {
241
        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

241
        foreach ($this->/** @scrutinizer ignore-call */ getNewChatMembers() as $member) {
Loading history...
242
            if ($member instanceof User && $member->getUsername() === $this->getBotUsername()) {
243
                return true;
244
            }
245
        }
246
247
        return false;
248
    }
249
250
    /**
251
     * Detect type based on properties.
252
     *
253
     * @return string
254
     */
255 1
    public function getType(): string
256
    {
257 1
        $types = [
258 1
            'text',
259 1
            'animation',
260 1
            'audio',
261 1
            'document',
262 1
            'photo',
263 1
            'sticker',
264 1
            'video',
265 1
            'video_note',
266 1
            'voice',
267 1
            'contact',
268 1
            'dice',
269 1
            'game',
270 1
            'poll',
271 1
            'venue',
272 1
            'location',
273 1
            'new_chat_members',
274 1
            'left_chat_member',
275 1
            'new_chat_title',
276 1
            'new_chat_photo',
277 1
            'delete_chat_photo',
278 1
            'group_chat_created',
279 1
            'supergroup_chat_created',
280 1
            'channel_chat_created',
281 1
            'message_auto_delete_timer_changed',
282 1
            'migrate_to_chat_id',
283 1
            'migrate_from_chat_id',
284 1
            'pinned_message',
285 1
            'invoice',
286 1
            'successful_payment',
287 1
            'user_shared',
288 1
            'chat_shared',
289 1
            'write_access_allowed',
290 1
            'passport_data',
291 1
            'proximity_alert_triggered',
292 1
            'forum_topic_created',
293 1
            'forum_topic_edited',
294 1
            'forum_topic_closed',
295 1
            'forum_topic_reopened',
296 1
            'general_forum_topic_hidden',
297 1
            'general_forum_topic_unhidden',
298 1
            'video_chat_scheduled',
299 1
            'video_chat_started',
300 1
            'video_chat_ended',
301 1
            'video_chat_participants_invited',
302 1
            'web_app_data',
303 1
            'reply_markup',
304 1
        ];
305
306 1
        $is_command = $this->getCommand() !== null;
307 1
        foreach ($types as $type) {
308 1
            if ($this->getProperty($type) !== null) {
309 1
                if ($is_command && $type === 'text') {
310 1
                    return 'command';
311
                }
312
313 1
                return $type;
314
            }
315
        }
316
317 1
        return 'message';
318
    }
319
}
320