Completed
Push — master ( 8fbc07...3e7af9 )
by Armando
02:10
created

Message::getNewChatMembers()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

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