Completed
Push — api_3.0_basic_changes ( 9bd403...4db909 )
by Armando
02:46
created

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