Completed
Push — develop ( 79747a...c8329d )
by Armando
19s queued 10s
created

Message::subEntities()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 30
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 28
nc 1
nop 0
dl 0
loc 30
ccs 2
cts 2
cp 1
crap 1
rs 9.472
c 0
b 0
f 0
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
 */
69
class Message extends Entity
70
{
71
    /**
72
     * {@inheritdoc}
73
     */
74 10
    protected function subEntities()
75
    {
76
        return [
77 10
            'from'               => User::class,
78
            'chat'               => Chat::class,
79
            'forward_from'       => User::class,
80
            'forward_from_chat'  => Chat::class,
81
            'reply_to_message'   => ReplyToMessage::class,
82
            'entities'           => [MessageEntity::class],
83
            'caption_entities'   => [MessageEntity::class],
84
            'audio'              => Audio::class,
85
            'document'           => Document::class,
86
            'animation'          => Animation::class,
87
            'game'               => Game::class,
88
            'photo'              => [PhotoSize::class],
89
            'sticker'            => Sticker::class,
90
            'video'              => Video::class,
91
            'voice'              => Voice::class,
92
            'video_note'         => VideoNote::class,
93
            'contact'            => Contact::class,
94
            'location'           => Location::class,
95
            'venue'              => Venue::class,
96
            'poll'               => Poll::class,
97
            'new_chat_members'   => [User::class],
98
            'left_chat_member'   => User::class,
99
            'new_chat_photo'     => [PhotoSize::class],
100
            'pinned_message'     => Message::class,
101
            'invoice'            => Invoice::class,
102
            'successful_payment' => SuccessfulPayment::class,
103
            'passport_data'      => PassportData::class,
104
        ];
105
    }
106
107
    /**
108
     * return the entire command like /echo or /echo@bot1 if specified
109
     *
110
     * @return string|null
111
     */
112 2
    public function getFullCommand()
113
    {
114 2
        $text = $this->getProperty('text');
115 2
        if (strpos($text, '/') !== 0) {
116 2
            return null;
117
        }
118
119 2
        $no_EOL   = strtok($text, PHP_EOL);
120 2
        $no_space = strtok($text, ' ');
121
122
        //try to understand which separator \n or space divide /command from text
123 2
        return strlen($no_space) < strlen($no_EOL) ? $no_space : $no_EOL;
124
    }
125
126
    /**
127
     * Get command
128
     *
129
     * @return string|null
130
     */
131 2
    public function getCommand()
132
    {
133 2
        if ($command = $this->getProperty('command')) {
134
            return $command;
135
        }
136
137 2
        $full_command = $this->getFullCommand();
138 2
        if (strpos($full_command, '/') !== 0) {
139 2
            return null;
140
        }
141 2
        $full_command = substr($full_command, 1);
142
143
        //check if command is followed by bot username
144 2
        $split_cmd = explode('@', $full_command);
145 2
        if (!isset($split_cmd[1])) {
146
            //command is not followed by name
147 2
            return $full_command;
148
        }
149
150 1
        if (strtolower($split_cmd[1]) === strtolower($this->getBotUsername())) {
151
            //command is addressed to me
152 1
            return $split_cmd[0];
153
        }
154
155
        return null;
156
    }
157
158
    /**
159
     * For text messages, the actual UTF-8 text of the message, 0-4096 characters.
160
     *
161
     * @param bool $without_cmd
162
     *
163
     * @return string
164
     */
165 9
    public function getText($without_cmd = false)
166
    {
167 9
        $text = $this->getProperty('text');
168
169 9
        if ($without_cmd && $command = $this->getFullCommand()) {
170 1
            if (strlen($command) + 1 < strlen($text)) {
171 1
                return substr($text, strlen($command) + 1);
172
            }
173
174 1
            return '';
175
        }
176
177 9
        return $text;
178
    }
179
180
    /**
181
     * Bot added in chat
182
     *
183
     * @return bool
184
     */
185
    public function botAddedInChat()
186
    {
187
        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

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