Completed
Push — scrutinizer_improvements ( 94741e )
by Armando
02:29
created

Message::getCommand()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 26
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5.0909

Importance

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