Completed
Push — master ( 695e63...f2fe6e )
by Armando
02:21 queued 01:02
created

Message::getText()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 7
cts 7
cp 1
rs 9.7998
c 0
b 0
f 0
cc 4
nc 3
nop 1
crap 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
     * @throws \Longman\TelegramBot\Exception\TelegramException
109
     */
110 12
    public function __construct(array $data, $bot_username = '')
111
    {
112 12
        parent::__construct($data, $bot_username);
113 12
    }
114
115
    /**
116
     * Optional. Message is a photo, available sizes of the photo
117
     *
118
     * This method overrides the default getPhoto method
119
     * and returns a nice array of PhotoSize objects.
120
     *
121
     * @return null|PhotoSize[]
122
     */
123 6
    public function getPhoto()
124
    {
125 6
        $pretty_array = $this->makePrettyObjectArray(PhotoSize::class, 'photo');
126
127 6
        return empty($pretty_array) ? null : $pretty_array;
128
    }
129
130
    /**
131
     * Optional. A chat photo was changed to this value
132
     *
133
     * This method overrides the default getNewChatPhoto method
134
     * and returns a nice array of PhotoSize objects.
135
     *
136
     * @return null|PhotoSize[]
137
     */
138 6
    public function getNewChatPhoto()
139
    {
140 6
        $pretty_array = $this->makePrettyObjectArray(PhotoSize::class, 'new_chat_photo');
141
142 6
        return empty($pretty_array) ? null : $pretty_array;
143
    }
144
145
    /**
146
     * Optional. A new member(s) was added to the group, information about them (one of this members may be the bot itself)
147
     *
148
     * This method overrides the default getNewChatMembers method
149
     * and returns a nice array of User objects.
150
     *
151
     * @return null|User[]
152
     */
153 6
    public function getNewChatMembers()
154
    {
155 6
        $pretty_array = $this->makePrettyObjectArray(User::class, 'new_chat_members');
156
157 6
        return empty($pretty_array) ? null : $pretty_array;
158
    }
159
160
    /**
161
     * Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text
162
     *
163
     * This method overrides the default getEntities method
164
     * and returns a nice array of MessageEntity objects.
165
     *
166
     * @return null|MessageEntity[]
167
     */
168 6
    public function getEntities()
169
    {
170 6
        $pretty_array = $this->makePrettyObjectArray(MessageEntity::class, 'entities');
171
172 6
        return empty($pretty_array) ? null : $pretty_array;
173
    }
174
175
    /**
176
     * Optional. For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption
177
     *
178
     * This method overrides the default getCaptionEntities method
179
     * and returns a nice array of MessageEntity objects.
180
     *
181
     * @return null|MessageEntity[]
182
     */
183 6
    public function getCaptionEntities()
184
    {
185 6
        $pretty_array = $this->makePrettyObjectArray(MessageEntity::class, 'caption_entities');
186
187 6
        return empty($pretty_array) ? null : $pretty_array;
188
    }
189
190
    /**
191
     * return the entire command like /echo or /echo@bot1 if specified
192
     *
193
     * @return string|null
194
     */
195 2
    public function getFullCommand()
196
    {
197 2
        $text = $this->getProperty('text');
198 2
        if (strpos($text, '/') !== 0) {
199 2
            return null;
200
        }
201
202 2
        $no_EOL   = strtok($text, PHP_EOL);
203 2
        $no_space = strtok($text, ' ');
204
205
        //try to understand which separator \n or space divide /command from text
206 2
        return strlen($no_space) < strlen($no_EOL) ? $no_space : $no_EOL;
207
    }
208
209
    /**
210
     * Get command
211
     *
212
     * @return string|null
213
     */
214 2
    public function getCommand()
215
    {
216 2
        if ($command = $this->getProperty('command')) {
217
            return $command;
218
        }
219
220 2
        $full_command = $this->getFullCommand();
221 2
        if (strpos($full_command, '/') !== 0) {
222 2
            return null;
223
        }
224 2
        $full_command = substr($full_command, 1);
225
226
        //check if command is followed by bot username
227 2
        $split_cmd = explode('@', $full_command);
228 2
        if (!isset($split_cmd[1])) {
229
            //command is not followed by name
230 2
            return $full_command;
231
        }
232
233 1
        if (strtolower($split_cmd[1]) === strtolower($this->getBotUsername())) {
234
            //command is addressed to me
235 1
            return $split_cmd[0];
236
        }
237
238
        return null;
239
    }
240
241
    /**
242
     * For text messages, the actual UTF-8 text of the message, 0-4096 characters.
243
     *
244
     * @param bool $without_cmd
245
     *
246
     * @return string
247
     */
248 9
    public function getText($without_cmd = false)
249
    {
250 9
        $text = $this->getProperty('text');
251
252 9
        if ($without_cmd && $command = $this->getFullCommand()) {
253 1
            if (strlen($command) + 1 < strlen($text)) {
254 1
                return substr($text, strlen($command) + 1);
255
            }
256
257 1
            return '';
258
        }
259
260 9
        return $text;
261
    }
262
263
    /**
264
     * Bot added in chat
265
     *
266
     * @return bool
267
     * @throws \Longman\TelegramBot\Exception\TelegramException
268
     */
269
    public function botAddedInChat()
270
    {
271
        foreach ($this->getNewChatMembers() as $member) {
272
            if ($member instanceof User && $member->getUsername() === $this->getBotUsername()) {
273
                return true;
274
            }
275
        }
276
277
        return false;
278
    }
279
280
    /**
281
     * Detect type based on properties.
282
     *
283
     * @return string
284
     */
285 1
    public function getType()
286
    {
287
        $types = [
288 1
            'text',
289
            'audio',
290
            'document',
291
            'animation',
292
            'game',
293
            'photo',
294
            'sticker',
295
            'video',
296
            'voice',
297
            'video_note',
298
            'contact',
299
            'location',
300
            'venue',
301
            'poll',
302
            'new_chat_members',
303
            'left_chat_member',
304
            'new_chat_title',
305
            'new_chat_photo',
306
            'delete_chat_photo',
307
            'group_chat_created',
308
            'supergroup_chat_created',
309
            'channel_chat_created',
310
            'migrate_to_chat_id',
311
            'migrate_from_chat_id',
312
            'pinned_message',
313
            'invoice',
314
            'successful_payment',
315
            'passport_data',
316
        ];
317
318 1
        $is_command = strlen($this->getCommand()) > 0;
319 1
        foreach ($types as $type) {
320 1
            if ($this->getProperty($type) !== null) {
321 1
                if ($is_command && $type === 'text') {
322 1
                    return 'command';
323
                }
324
325 1
                return $type;
326
            }
327
        }
328
329 1
        return 'message';
330
    }
331
}
332