Completed
Push — smaller_code_and_docblock_fixe... ( b2ca6a...ea3afd )
by Armando
03:45
created

Message   A

Complexity

Total Complexity 33

Size/Duplication

Total Lines 263
Duplicated Lines 0 %

Test Coverage

Coverage 88.52%

Importance

Changes 0
Metric Value
eloc 104
dl 0
loc 263
ccs 54
cts 61
cp 0.8852
rs 9.76
c 0
b 0
f 0
wmc 33

12 Methods

Rating   Name   Duplication   Size   Complexity  
A getPhoto() 0 5 2
A __construct() 0 3 1
A getCaptionEntities() 0 5 2
A botAddedInChat() 0 9 4
A getNewChatPhoto() 0 5 2
A subEntities() 0 30 1
A getFullCommand() 0 12 3
A getCommand() 0 25 5
A getType() 0 45 5
A getEntities() 0 5 2
A getNewChatMembers() 0 5 2
A getText() 0 13 4
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\Entities;
12
13
use Longman\TelegramBot\Entities\Games\Game;
14
use Longman\TelegramBot\Entities\Payments\Invoice;
15
use Longman\TelegramBot\Entities\Payments\SuccessfulPayment;
16
use Longman\TelegramBot\Entities\TelegramPassport\PassportData;
17
18
/**
19
 * Class Message
20
 *
21
 * @link https://core.telegram.org/bots/api#message
22
 *
23
 * @method int               getMessageId()             Unique message identifier
24
 * @method User              getFrom()                  Optional. Sender, can be empty for messages sent to channels
25
 * @method int               getDate()                  Date the message was sent in Unix time
26
 * @method Chat              getChat()                  Conversation the message belongs to
27
 * @method User              getForwardFrom()           Optional. For forwarded messages, sender of the original message
28
 * @method Chat              getForwardFromChat()       Optional. For messages forwarded from a channel, information about the original channel
29
 * @method int               getForwardFromMessageId()  Optional. For forwarded channel posts, identifier of the original message in the channel
30
 * @method string            getForwardSignature()      Optional. For messages forwarded from channels, signature of the post author if present
31
 * @method string            getForwardSenderName()     Optional. Sender's name for messages forwarded from users who disallow adding a link to their account in forwarded messages
32
 * @method int               getForwardDate()           Optional. For forwarded messages, date the original message was sent in Unix time
33
 * @method Message           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.
34
 * @method int               getEditDate()              Optional. Date the message was last edited in Unix time
35
 * @method string            getMediaGroupId()          Optional. The unique identifier of a media message group this message belongs to
36
 * @method string            getAuthorSignature()       Optional. Signature of the post author for messages in channels
37
 * @method Audio             getAudio()                 Optional. Message is an audio file, information about the file
38
 * @method Document          getDocument()              Optional. Message is a general file, information about the file
39
 * @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
40
 * @method Game              getGame()                  Optional. Message is a game, information about the game.
41
 * @method Sticker           getSticker()               Optional. Message is a sticker, information about the sticker
42
 * @method Video             getVideo()                 Optional. Message is a video, information about the video
43
 * @method Voice             getVoice()                 Optional. Message is a voice message, information about the file
44
 * @method VideoNote         getVideoNote()             Optional. Message is a video note message, information about the video
45
 * @method string            getCaption()               Optional. Caption for the document, photo or video, 0-200 characters
46
 * @method Contact           getContact()               Optional. Message is a shared contact, information about the contact
47
 * @method Location          getLocation()              Optional. Message is a shared location, information about the location
48
 * @method Venue             getVenue()                 Optional. Message is a venue, information about the venue
49
 * @method Poll              getPoll()                  Optional. Message is a native poll, information about the poll
50
 * @method User              getLeftChatMember()        Optional. A member was removed from the group, information about them (this member may be the bot itself)
51
 * @method string            getNewChatTitle()          Optional. A chat title was changed to this value
52
 * @method bool              getDeleteChatPhoto()       Optional. Service message: the chat photo was deleted
53
 * @method bool              getGroupChatCreated()      Optional. Service message: the group has been created
54
 * @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.
55
 * @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.
56
 * @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.
57
 * @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.
58
 * @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.
59
 * @method Invoice           getInvoice()               Optional. Message is an invoice for a payment, information about the invoice.
60
 * @method SuccessfulPayment getSuccessfulPayment()     Optional. Message is a service message about a successful payment, information about the payment.
61
 * @method string            getConnectedWebsite()      Optional. The domain name of the website on which the user has logged in.
62
 * @method PassportData      getPassportData()          Optional. Telegram Passport data
63
 */
64
class Message extends Entity
65
{
66
    /**
67
     * {@inheritdoc}
68
     */
69 10
    protected function subEntities()
70
    {
71
        return [
72 10
            'from'               => User::class,
73
            'chat'               => Chat::class,
74
            'forward_from'       => User::class,
75
            'forward_from_chat'  => Chat::class,
76
            'reply_to_message'   => ReplyToMessage::class,
77
            'entities'           => MessageEntity::class,
78
            'caption_entities'   => MessageEntity::class,
79
            'audio'              => Audio::class,
80
            'document'           => Document::class,
81
            'animation'          => Animation::class,
82
            'game'               => Game::class,
83
            'photo'              => PhotoSize::class,
84
            'sticker'            => Sticker::class,
85
            'video'              => Video::class,
86
            'voice'              => Voice::class,
87
            'video_note'         => VideoNote::class,
88
            'contact'            => Contact::class,
89
            'location'           => Location::class,
90
            'venue'              => Venue::class,
91
            'poll'               => Poll::class,
92
            'new_chat_members'   => User::class,
93
            'left_chat_member'   => User::class,
94
            'new_chat_photo'     => PhotoSize::class,
95
            'pinned_message'     => Message::class,
96
            'invoice'            => Invoice::class,
97
            'successful_payment' => SuccessfulPayment::class,
98
            'passport_data'      => PassportData::class,
99
        ];
100
    }
101
102
    /**
103
     * Message constructor
104
     *
105
     * @param array  $data
106
     * @param string $bot_username
107
     */
108 12
    public function __construct(array $data, $bot_username = '')
109
    {
110 12
        parent::__construct($data, $bot_username);
111 12
    }
112
113
    /**
114
     * Optional. Message is a photo, available sizes of the photo
115
     *
116
     * This method overrides the default getPhoto method
117
     * and returns a nice array of PhotoSize objects.
118
     *
119
     * @return null|PhotoSize[]
120
     */
121 6
    public function getPhoto()
122
    {
123 6
        $pretty_array = $this->makePrettyObjectArray(PhotoSize::class, 'photo');
124
125 6
        return empty($pretty_array) ? null : $pretty_array;
126
    }
127
128
    /**
129
     * Optional. A chat photo was changed to this value
130
     *
131
     * This method overrides the default getNewChatPhoto method
132
     * and returns a nice array of PhotoSize objects.
133
     *
134
     * @return null|PhotoSize[]
135
     */
136 6
    public function getNewChatPhoto()
137
    {
138 6
        $pretty_array = $this->makePrettyObjectArray(PhotoSize::class, 'new_chat_photo');
139
140 6
        return empty($pretty_array) ? null : $pretty_array;
141
    }
142
143
    /**
144
     * Optional. A new member(s) was added to the group, information about them (one of this members may be the bot itself)
145
     *
146
     * This method overrides the default getNewChatMembers method
147
     * and returns a nice array of User objects.
148
     *
149
     * @return null|User[]
150
     */
151 6
    public function getNewChatMembers()
152
    {
153 6
        $pretty_array = $this->makePrettyObjectArray(User::class, 'new_chat_members');
154
155 6
        return empty($pretty_array) ? null : $pretty_array;
156
    }
157
158
    /**
159
     * Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text
160
     *
161
     * This method overrides the default getEntities method
162
     * and returns a nice array of MessageEntity objects.
163
     *
164
     * @return null|MessageEntity[]
165
     */
166 6
    public function getEntities()
167
    {
168 6
        $pretty_array = $this->makePrettyObjectArray(MessageEntity::class, 'entities');
169
170 6
        return empty($pretty_array) ? null : $pretty_array;
171
    }
172
173
    /**
174
     * Optional. For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption
175
     *
176
     * This method overrides the default getCaptionEntities method
177
     * and returns a nice array of MessageEntity objects.
178
     *
179
     * @return null|MessageEntity[]
180
     */
181 6
    public function getCaptionEntities()
182
    {
183 6
        $pretty_array = $this->makePrettyObjectArray(MessageEntity::class, 'caption_entities');
184
185 6
        return empty($pretty_array) ? null : $pretty_array;
186
    }
187
188
    /**
189
     * return the entire command like /echo or /echo@bot1 if specified
190
     *
191
     * @return string|null
192
     */
193 2
    public function getFullCommand()
194
    {
195 2
        $text = $this->getProperty('text');
196 2
        if (strpos($text, '/') !== 0) {
197 2
            return null;
198
        }
199
200 2
        $no_EOL   = strtok($text, PHP_EOL);
201 2
        $no_space = strtok($text, ' ');
202
203
        //try to understand which separator \n or space divide /command from text
204 2
        return strlen($no_space) < strlen($no_EOL) ? $no_space : $no_EOL;
205
    }
206
207
    /**
208
     * Get command
209
     *
210
     * @return string|null
211
     */
212 2
    public function getCommand()
213
    {
214 2
        if ($command = $this->getProperty('command')) {
215
            return $command;
216
        }
217
218 2
        $full_command = $this->getFullCommand();
219 2
        if (strpos($full_command, '/') !== 0) {
220 2
            return null;
221
        }
222 2
        $full_command = substr($full_command, 1);
223
224
        //check if command is followed by bot username
225 2
        $split_cmd = explode('@', $full_command);
226 2
        if (!isset($split_cmd[1])) {
227
            //command is not followed by name
228 2
            return $full_command;
229
        }
230
231 1
        if (strtolower($split_cmd[1]) === strtolower($this->getBotUsername())) {
232
            //command is addressed to me
233 1
            return $split_cmd[0];
234
        }
235
236
        return null;
237
    }
238
239
    /**
240
     * For text messages, the actual UTF-8 text of the message, 0-4096 characters.
241
     *
242
     * @param bool $without_cmd
243
     *
244
     * @return string
245
     */
246 9
    public function getText($without_cmd = false)
247
    {
248 9
        $text = $this->getProperty('text');
249
250 9
        if ($without_cmd && $command = $this->getFullCommand()) {
251 1
            if (strlen($command) + 1 < strlen($text)) {
252 1
                return substr($text, strlen($command) + 1);
253
            }
254
255 1
            return '';
256
        }
257
258 9
        return $text;
259
    }
260
261
    /**
262
     * Bot added in chat
263
     *
264
     * @return bool
265
     */
266
    public function botAddedInChat()
267
    {
268
        foreach ($this->getNewChatMembers() as $member) {
269
            if ($member instanceof User && $member->getUsername() === $this->getBotUsername()) {
270
                return true;
271
            }
272
        }
273
274
        return false;
275
    }
276
277
    /**
278
     * Detect type based on properties.
279
     *
280
     * @return string
281
     */
282 1
    public function getType()
283
    {
284
        $types = [
285 1
            'text',
286
            'audio',
287
            'document',
288
            'animation',
289
            'game',
290
            'photo',
291
            'sticker',
292
            'video',
293
            'voice',
294
            'video_note',
295
            'contact',
296
            'location',
297
            'venue',
298
            'poll',
299
            'new_chat_members',
300
            'left_chat_member',
301
            'new_chat_title',
302
            'new_chat_photo',
303
            'delete_chat_photo',
304
            'group_chat_created',
305
            'supergroup_chat_created',
306
            'channel_chat_created',
307
            'migrate_to_chat_id',
308
            'migrate_from_chat_id',
309
            'pinned_message',
310
            'invoice',
311
            'successful_payment',
312
            'passport_data',
313
        ];
314
315 1
        $is_command = strlen($this->getCommand()) > 0;
316 1
        foreach ($types as $type) {
317 1
            if ($this->getProperty($type) !== null) {
318 1
                if ($is_command && $type === 'text') {
319 1
                    return 'command';
320
                }
321
322 1
                return $type;
323
            }
324
        }
325
326 1
        return 'message';
327
    }
328
}
329