Completed
Pull Request — develop (#291)
by Armando
13:31
created

Message::getType()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 38
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 5.9256

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 38
ccs 16
cts 24
cp 0.6667
rs 8.439
cc 5
eloc 29
nc 4
nop 0
crap 5.9256
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      getForwardDate()           Optional. For forwarded messages, date the original message was sent in Unix time
25
 * @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.
26
 * @method int      getEditDate()              Optional. Date the message was last edited in Unix time
27
 * @method Audio    getAudio()                 Optional. Message is an audio file, information about the file
28
 * @method Document getDocument()              Optional. Message is a general file, information about the file
29
 * @method Sticker  getSticker()               Optional. Message is a sticker, information about the sticker
30
 * @method Video    getVideo()                 Optional. Message is a video, information about the video
31
 * @method Voice    getVoice()                 Optional. Message is a voice message, information about the file
32
 * @method string   getCaption()               Optional. Caption for the document, photo or video, 0-200 characters
33
 * @method Contact  getContact()               Optional. Message is a shared contact, information about the contact
34
 * @method Location getLocation()              Optional. Message is a shared location, information about the location
35
 * @method Venue    getVenue()                 Optional. Message is a venue, information about the venue
36
 * @method User     getNewChatMember()         Optional. A new member was added to the group, information about them (this member may be the bot itself)
37
 * @method User     getLeftChatMember()        Optional. A member was removed from the group, information about them (this member may be the bot itself)
38
 * @method string   getNewChatTitle()          Optional. A chat title was changed to this value
39
 * @method bool     getDeleteChatPhoto()       Optional. Service message: the chat photo was deleted
40
 * @method bool     getGroupChatCreated()      Optional. Service message: the group has been created
41
 * @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.
42
 * @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.
43
 * @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.
44
 * @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.
45
 * @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.
46
 */
47
class Message extends Entity
48
{
49
    /**
50
     * {@inheritdoc}
51
     */
52
    protected function subEntities()
53
    {
54
        return [
55
            'from'              => User::class,
56
            'chat'              => Chat::class,
57
            'forward_from'      => User::class,
58
            'forward_from_chat' => User::class,
59
            'reply_to_message'  => self::class,
60
            'entities'          => MessageEntity::class,
61
            'audio'             => Audio::class,
62
            'document'          => Document::class,
63
            'photo'             => PhotoSize::class,
64
            'sticker'           => Sticker::class,
65
            'video'             => Video::class,
66
            'voice'             => Voice::class,
67
            'contact'           => Contact::class,
68
            'location'          => Location::class,
69
            'venue'             => Venue::class,
70
            'new_chat_member'   => User::class,
71
            'left_chat_member'  => User::class,
72
            'new_chat_photo'    => PhotoSize::class,
73
            'pinned_message'    => Message::class,
74
        ];
75
    }
76
77
    /**
78
     * Message constructor
79
     *
80
     * @param array  $data
81
     * @param string $bot_name
82
     *
83
     * @throws \Longman\TelegramBot\Exception\TelegramException
84
     */
85
    public function __construct(array $data, $bot_name = '')
86
    {
87
        //Retro-compatibility
88
        if (isset($data['new_chat_participant'])) {
89
            $data['new_chat_member'] = $data['new_chat_participant'];
90
            unset($data['new_chat_participant']);
91
        }
92
        if (isset($data['left_chat_participant'])) {
93
            $data['left_chat_member'] = $data['left_chat_participant'];
94
            unset($data['left_chat_participant']);
95
        }
96
97
        parent::__construct($data, $bot_name);
98
    }
99
100
    /**
101
     * Optional. Message is a photo, available sizes of the photo
102
     *
103
     * This method overrides the default getPhoto method
104
     * and returns a nice array of PhotoSize objects.
105
     *
106
     * @return array
107
     */
108
    public function getPhoto()
109
    {
110
        return $this->makePrettyObjectArray(PhotoSize::class, 'photo');
111
    }
112
113
    /**
114
     * Optional. A chat photo was changed to this value
115
     *
116
     * This method overrides the default getNewChatPhoto method
117
     * and returns a nice array of PhotoSize objects.
118
     *
119
     * @return array
120
     */
121
    public function getNewChatPhoto()
122
    {
123
        return $this->makePrettyObjectArray(PhotoSize::class, 'new_chat_photo');
124
    }
125
126
    /**
127
     * Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text
128
     *
129
     * This method overrides the default getEntities method
130
     * and returns a nice array of MessageEntity objects.
131
     *
132
     * @return array
133
     */
134
    public function getEntities()
135
    {
136
        return $this->makePrettyObjectArray(MessageEntity::class, 'entities');
137
    }
138
139
    /**
140
     * return the entire command like /echo or /echo@bot1 if specified
141
     *
142
     * @return string|null
143
     */
144
    public function getFullCommand()
145
    {
146
        if (strpos($this->text, '/') === 0) {
147
            $no_EOL   = strtok($this->text, PHP_EOL);
0 ignored issues
show
Bug introduced by
The property text does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
148
            $no_space = strtok($this->text, ' ');
149
150
            //try to understand which separator \n or space divide /command from text
151
            if (strlen($no_space) < strlen($no_EOL)) {
152
                return $no_space;
153
            } else {
154
                return $no_EOL;
155
            }
156
        } else {
157
            return null;
158
        }
159
    }
160
161
    /**
162
     * Get command
163
     *
164
     * @return bool|string
165
     */
166
    public function getCommand()
167
    {
168
        if (!empty($this->command)) {
169
            return $this->command;
0 ignored issues
show
Bug introduced by
The property command does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
170
        }
171
172
        $cmd = $this->getFullCommand();
173
174
        if (strpos($cmd, '/') === 0) {
175
            $cmd = substr($cmd, 1);
176
177
            //check if command is follow by botname
178
            $split_cmd = explode('@', $cmd);
179
            if (isset($split_cmd[1])) {
180
                //command is followed by name check if is addressed to me
181
                if (strtolower($split_cmd[1]) === strtolower($this->bot_name)) {
182
                    return $this->command = $split_cmd[0];
183
                }
184
            } else {
185
                //command is not followed by name
186
                return $this->command = $cmd;
187
            }
188
        }
189
190
        return false;
191
    }
192
193 18
    /**
194
     * For text messages, the actual UTF-8 text of the message, 0-4096 characters.
195
     *
196 18
     * @param bool $without_cmd
197 18
     *
198 2
     * @return string
199
     */
200
    public function getText($without_cmd = false)
201 18
    {
202 18
        $text = $this->text;
203
204
        if ($without_cmd && $command = $this->getFullCommand()) {
205
            if (strlen($command) + 1 < strlen($text)) {
206
                $text = substr($text, strlen($command) + 1);
207
            } else {
208
                $text = '';
209
            }
210
        }
211 18
212
        return $text;
213 18
    }
214
215 18
    /**
216
     * Bot added in chat
217 18
     *
218 18
     * @return bool
219
     */
220
    public function botAddedInChat()
221
    {
222 18
        if (!empty($this->new_chat_member)) {
223 18
            if ($this->new_chat_member->getUsername() === $this->getBotName()) {
0 ignored issues
show
Bug introduced by
The property new_chat_member does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
224 17
                return true;
225
            }
226
        }
227 18
228 18
        return false;
229
    }
230
231 18
    /**
232
     * Detect type based on properties.
233 18
     *
234 18
     * @return string|null
235
     */
236
    public function getType()
237
    {
238 18
        $types = [
239 18
            'text',
240
            'audio',
241
            'document',
242
            'photo',
243 18
            'sticker',
244 18
            'video',
245
            'voice',
246
            'contact',
247
            'location',
248 18
            'venue',
249
            'new_chat_member',
250 18
            'left_chat_member',
251
            'new_chat_title',
252 18
            'new_chat_photo',
253 18
            'delete_chat_photo',
254 18
            'group_chat_created',
255 7
            'supergroup_chat_created',
256
            'channel_chat_created',
257
            'migrate_to_chat_id',
258 18
            'migrate_from_chat_id',
259 18
            'pinned_message',
260
        ];
261
262
        foreach ($types as $type) {
263
            if ($this->getProperty($type)) {
264 18
                if ($type === 'text' && $this->getCommand()) {
265 18
                    return 'command';
266
                }
267
268
                return $type;
269
            }
270 18
        }
271 18
272
        return 'message';
273
    }
274
}
275