Passed
Push — master ( 7f7158...8d1ed5 )
by Armando
02:55
created

Message::subEntities()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 31
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 29
c 2
b 0
f 0
nc 1
nop 0
dl 0
loc 31
ccs 2
cts 2
cp 1
crap 1
rs 9.456
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 MessageEntity[]   getEntities()              Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text
38
 * @method MessageEntity[]   getCaptionEntities()       Optional. For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption
39
 * @method Audio             getAudio()                 Optional. Message is an audio file, information about the file
40
 * @method Document          getDocument()              Optional. Message is a general file, information about the file
41
 * @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
42
 * @method Game              getGame()                  Optional. Message is a game, information about the game.
43
 * @method PhotoSize[]       getPhoto()                 Optional. Message is a photo, available sizes of the photo
44
 * @method Sticker           getSticker()               Optional. Message is a sticker, information about the sticker
45
 * @method Video             getVideo()                 Optional. Message is a video, information about the video
46
 * @method Voice             getVoice()                 Optional. Message is a voice message, information about the file
47
 * @method VideoNote         getVideoNote()             Optional. Message is a video note message, information about the video
48
 * @method string            getCaption()               Optional. Caption for the document, photo or video, 0-200 characters
49
 * @method Contact           getContact()               Optional. Message is a shared contact, information about the contact
50
 * @method Location          getLocation()              Optional. Message is a shared location, information about the location
51
 * @method Venue             getVenue()                 Optional. Message is a venue, information about the venue
52
 * @method Poll              getPoll()                  Optional. Message is a native poll, information about the poll
53
 * @method User[]            getNewChatMembers()        Optional. A new member(s) was added to the group, information about them (one of this members may be the bot itself)
54
 * @method User              getLeftChatMember()        Optional. A member was removed from the group, information about them (this member may be the bot itself)
55
 * @method string            getNewChatTitle()          Optional. A chat title was changed to this value
56
 * @method PhotoSize[]       getNewChatPhoto()          Optional. A chat photo was changed to this value
57
 * @method bool              getDeleteChatPhoto()       Optional. Service message: the chat photo was deleted
58
 * @method bool              getGroupChatCreated()      Optional. Service message: the group has been created
59
 * @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.
60
 * @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.
61
 * @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.
62
 * @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.
63
 * @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.
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
 * @method PassportData      getPassportData()          Optional. Telegram Passport data
68
 * @method InlineKeyboard    getReplyMarkup()           Optional. Inline keyboard attached to the message. login_url buttons are represented as ordinary url buttons.
69
 */
70
class Message extends Entity
71
{
72
    /**
73
     * {@inheritdoc}
74
     */
75 10
    protected function subEntities()
76
    {
77
        return [
78 10
            'from'               => User::class,
79
            'chat'               => Chat::class,
80
            'forward_from'       => User::class,
81
            'forward_from_chat'  => Chat::class,
82
            'reply_to_message'   => ReplyToMessage::class,
83
            'entities'           => [MessageEntity::class],
84
            'caption_entities'   => [MessageEntity::class],
85
            'audio'              => Audio::class,
86
            'document'           => Document::class,
87
            'animation'          => Animation::class,
88
            'game'               => Game::class,
89
            'photo'              => [PhotoSize::class],
90
            'sticker'            => Sticker::class,
91
            'video'              => Video::class,
92
            'voice'              => Voice::class,
93
            'video_note'         => VideoNote::class,
94
            'contact'            => Contact::class,
95
            'location'           => Location::class,
96
            'venue'              => Venue::class,
97
            'poll'               => Poll::class,
98
            'new_chat_members'   => [User::class],
99
            'left_chat_member'   => User::class,
100
            'new_chat_photo'     => [PhotoSize::class],
101
            'pinned_message'     => Message::class,
102
            'invoice'            => Invoice::class,
103
            'successful_payment' => SuccessfulPayment::class,
104
            'passport_data'      => PassportData::class,
105
            'reply_markup'       => InlineKeyboard::class,
106
        ];
107
    }
108
109
    /**
110
     * return the entire command like /echo or /echo@bot1 if specified
111
     *
112
     * @return string|null
113
     */
114 2
    public function getFullCommand()
115
    {
116 2
        $text = $this->getProperty('text');
117 2
        if (strpos($text, '/') !== 0) {
118 2
            return null;
119
        }
120
121 2
        $no_EOL   = strtok($text, PHP_EOL);
122 2
        $no_space = strtok($text, ' ');
123
124
        //try to understand which separator \n or space divide /command from text
125 2
        return strlen($no_space) < strlen($no_EOL) ? $no_space : $no_EOL;
126
    }
127
128
    /**
129
     * Get command
130
     *
131
     * @return string|null
132
     */
133 2
    public function getCommand()
134
    {
135 2
        if ($command = $this->getProperty('command')) {
136
            return $command;
137
        }
138
139 2
        $full_command = $this->getFullCommand();
140 2
        if (strpos($full_command, '/') !== 0) {
141 2
            return null;
142
        }
143 2
        $full_command = substr($full_command, 1);
144
145
        //check if command is followed by bot username
146 2
        $split_cmd = explode('@', $full_command);
147 2
        if (!isset($split_cmd[1])) {
148
            //command is not followed by name
149 2
            return $full_command;
150
        }
151
152 1
        if (strtolower($split_cmd[1]) === strtolower($this->getBotUsername())) {
153
            //command is addressed to me
154 1
            return $split_cmd[0];
155
        }
156
157
        return null;
158
    }
159
160
    /**
161
     * For text messages, the actual UTF-8 text of the message, 0-4096 characters.
162
     *
163
     * @param bool $without_cmd
164
     *
165
     * @return string
166
     */
167 9
    public function getText($without_cmd = false)
168
    {
169 9
        $text = $this->getProperty('text');
170
171 9
        if ($without_cmd && $command = $this->getFullCommand()) {
172 1
            if (strlen($command) + 1 < strlen($text)) {
173 1
                return substr($text, strlen($command) + 1);
174
            }
175
176 1
            return '';
177
        }
178
179 9
        return $text;
180
    }
181
182
    /**
183
     * Bot added in chat
184
     *
185
     * @return bool
186
     */
187
    public function botAddedInChat()
188
    {
189
        foreach ($this->getNewChatMembers() as $member) {
0 ignored issues
show
Bug introduced by
The method getNewChatMembers() does not exist on Longman\TelegramBot\Entities\Message. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

189
        foreach ($this->/** @scrutinizer ignore-call */ getNewChatMembers() as $member) {
Loading history...
190
            if ($member instanceof User && $member->getUsername() === $this->getBotUsername()) {
191
                return true;
192
            }
193
        }
194
195
        return false;
196
    }
197
198
    /**
199
     * Detect type based on properties.
200
     *
201
     * @return string
202
     */
203 1
    public function getType()
204
    {
205
        $types = [
206 1
            'text',
207
            'audio',
208
            'document',
209
            'animation',
210
            'game',
211
            'photo',
212
            'sticker',
213
            'video',
214
            'voice',
215
            'video_note',
216
            'contact',
217
            'location',
218
            'venue',
219
            'poll',
220
            'new_chat_members',
221
            'left_chat_member',
222
            'new_chat_title',
223
            'new_chat_photo',
224
            'delete_chat_photo',
225
            'group_chat_created',
226
            'supergroup_chat_created',
227
            'channel_chat_created',
228
            'migrate_to_chat_id',
229
            'migrate_from_chat_id',
230
            'pinned_message',
231
            'invoice',
232
            'successful_payment',
233
            'passport_data',
234
            'reply_markup',
235
        ];
236
237 1
        $is_command = strlen($this->getCommand()) > 0;
238 1
        foreach ($types as $type) {
239 1
            if ($this->getProperty($type) !== null) {
240 1
                if ($is_command && $type === 'text') {
241 1
                    return 'command';
242
                }
243
244 1
                return $type;
245
            }
246
        }
247
248 1
        return 'message';
249
    }
250
}
251