Completed
Push — bot_api_4.0_passport ( 1b8370...32afb8 )
by Armando
10:56 queued 08:38
created

Message::getCaptionEntities()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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