Completed
Push — feature/refactor-app-design ( 84f9ff...b18d21 )
by Avtandil
04:09
created

Message::getPhoto()   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
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
31
 *     contain further reply_to_message fields even if it itself is a reply.
32
 * @method int               getEditDate()              Optional. Date the message was last edited in Unix time
33
 * @method string            getMediaGroupId()          Optional. The unique identifier of a media message group this message belongs to
34
 * @method string            getAuthorSignature()       Optional. Signature of the post author for messages in channels
35
 * @method Audio             getAudio()                 Optional. Message is an audio file, information about the file
36
 * @method Document          getDocument()              Optional. Message is a general file, information about the file
37
 * @method Sticker           getSticker()               Optional. Message is a sticker, information about the sticker
38
 * @method Video             getVideo()                 Optional. Message is a video, information about the video
39
 * @method Voice             getVoice()                 Optional. Message is a voice message, information about the file
40
 * @method VideoNote         getVideoNote()             Optional. Message is a video note message, information about the video
41
 * @method string            getCaption()               Optional. Caption for the document, photo or video, 0-200 characters
42
 * @method Contact           getContact()               Optional. Message is a shared contact, information about the contact
43
 * @method Location          getLocation()              Optional. Message is a shared location, information about the location
44
 * @method Venue             getVenue()                 Optional. Message is a venue, information about the venue
45
 * @method User              getLeftChatMember()        Optional. A member was removed from the group, information about them (this member may be the bot
46
 *     itself)
47
 * @method string            getNewChatTitle()          Optional. A chat title was changed to this value
48
 * @method bool              getDeleteChatPhoto()       Optional. Service message: the chat photo was deleted
49
 * @method bool              getGroupChatCreated()      Optional. Service message: the group has been created
50
 * @method bool              getSupergroupChatCreated() Optional. Service message: the supergroup has been created. This field can't be received in a message
51
 *     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
52
 *     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
54
 *     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
55
 *     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
57
 *     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
58
 *     bit integer or double-precision float type are safe for storing this identifier.
59
 * @method int               getMigrateFromChatId()     Optional. The supergroup has been migrated from a group with the specified identifier. This number may
60
 *     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
61
 *     64 bit integer or double-precision float type are safe for storing this identifier.
62
 * @method Message           getPinnedMessage()         Optional. Specified message was pinned. Note that the Message object in this field will not contain
63
 *     further reply_to_message fields even if it is itself a reply.
64
 * @method Invoice           getInvoice()               Optional. Message is an invoice for a payment, information about the invoice.
65
 * @method SuccessfulPayment getSuccessfulPayment()     Optional. Message is a service message about a successful payment, information about the payment.
66
 * @method string            getConnectedWebsite()      Optional. The domain name of the website on which the user has logged in.
67
 */
68
class Message extends Entity
69
{
70
    /**
71
     * {@inheritdoc}
72
     */
73 10
    protected function subEntities()
74
    {
75
        return [
76 10
            'from'               => User::class,
77
            'chat'               => Chat::class,
78
            'forward_from'       => User::class,
79
            'forward_from_chat'  => Chat::class,
80
            'reply_to_message'   => ReplyToMessage::class,
81
            'entities'           => MessageEntity::class,
82
            'caption_entities'   => MessageEntity::class,
83
            'audio'              => Audio::class,
84
            'document'           => Document::class,
85
            'photo'              => PhotoSize::class,
86
            'sticker'            => Sticker::class,
87
            'video'              => Video::class,
88
            'voice'              => Voice::class,
89
            'video_note'         => VideoNote::class,
90
            'contact'            => Contact::class,
91
            'location'           => Location::class,
92
            'venue'              => Venue::class,
93
            'new_chat_members'   => User::class,
94
            'left_chat_member'   => User::class,
95
            'new_chat_photo'     => PhotoSize::class,
96
            'pinned_message'     => Message::class,
97
            'invoice'            => Invoice::class,
98
            'successful_payment' => SuccessfulPayment::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
    public function getCaptionEntities()
184
    {
185
        $pretty_array = $this->makePrettyObjectArray(MessageEntity::class, 'caption_entities');
186
187
        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
            'photo',
292
            'sticker',
293
            'video',
294
            'voice',
295
            'contact',
296
            'location',
297
            'venue',
298
            'new_chat_members',
299
            'left_chat_member',
300
            'new_chat_title',
301
            'new_chat_photo',
302
            'delete_chat_photo',
303
            'group_chat_created',
304
            'supergroup_chat_created',
305
            'channel_chat_created',
306
            'migrate_to_chat_id',
307
            'migrate_from_chat_id',
308
            'pinned_message',
309
            'invoice',
310
            'successful_payment',
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