Completed
Push — refactor_entities ( c38610...2711d6 )
by Armando
03:36
created

Message::subEntities()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 24
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 24
ccs 2
cts 2
cp 1
rs 8.9713
cc 1
eloc 21
nc 1
nop 0
crap 1
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 14
    protected function subEntities()
53
    {
54
        return [
55 14
            '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 16
    public function __construct(array $data, $bot_name = '')
86
    {
87
        //Retro-compatibility
88 16
        if (isset($data['new_chat_participant'])) {
89
            $data['new_chat_member'] = $data['new_chat_participant'];
90
            unset($data['new_chat_participant']);
91
        }
92 16
        if (isset($data['left_chat_participant'])) {
93
            $data['left_chat_member'] = $data['left_chat_participant'];
94
            unset($data['left_chat_participant']);
95
        }
96
97 16
        parent::__construct($data, $bot_name);
98 16
    }
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 null|array
107
     */
108 6
    public function getPhoto()
109
    {
110 6
        $pretty_array = $this->makePrettyObjectArray(PhotoSize::class, 'photo');
111
112 6
        return empty($pretty_array) ? null : $pretty_array;
113
    }
114
115
    /**
116
     * Optional. A chat photo was changed to this value
117
     *
118
     * This method overrides the default getNewChatPhoto method
119
     * and returns a nice array of PhotoSize objects.
120
     *
121
     * @return null|array
122
     */
123 6
    public function getNewChatPhoto()
124
    {
125 6
        $pretty_array = $this->makePrettyObjectArray(PhotoSize::class, 'new_chat_photo');
126
127 6
        return empty($pretty_array) ? null : $pretty_array;
128
    }
129
130
    /**
131
     * Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text
132
     *
133
     * This method overrides the default getEntities method
134
     * and returns a nice array of MessageEntity objects.
135
     *
136
     * @return null|array
137
     */
138 6
    public function getEntities()
139
    {
140 6
        $pretty_array = $this->makePrettyObjectArray(MessageEntity::class, 'entities');
141
142 6
        return empty($pretty_array) ? null : $pretty_array;
143
    }
144
145
    /**
146
     * return the entire command like /echo or /echo@bot1 if specified
147
     *
148
     * @return string|null
149
     */
150 6
    public function getFullCommand()
151
    {
152 6
        if (strpos($this->text, '/') === 0) {
153 6
            $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...
154 6
            $no_space = strtok($this->text, ' ');
155
156
            //try to understand which separator \n or space divide /command from text
157 6
            if (strlen($no_space) < strlen($no_EOL)) {
158 5
                return $no_space;
159
            } else {
160 3
                return $no_EOL;
161
            }
162
        } else {
163 1
            return null;
164
        }
165
    }
166
167
    /**
168
     * Get command
169
     *
170
     * @return bool|string
171
     */
172 1
    public function getCommand()
173
    {
174 1
        if (!empty($this->command)) {
175
            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...
176
        }
177
178 1
        $cmd = $this->getFullCommand();
179
180 1
        if (strpos($cmd, '/') === 0) {
181 1
            $cmd = substr($cmd, 1);
182
183
            //check if command is follow by botname
184 1
            $split_cmd = explode('@', $cmd);
185 1
            if (isset($split_cmd[1])) {
186
                //command is followed by name check if is addressed to me
187 1
                if (strtolower($split_cmd[1]) === strtolower($this->bot_name)) {
188 1
                    return $this->command = $split_cmd[0];
189
                }
190
            } else {
191
                //command is not followed by name
192 1
                return $this->command = $cmd;
193
            }
194
        }
195
196 1
        return false;
197
    }
198
199
    /**
200
     * For text messages, the actual UTF-8 text of the message, 0-4096 characters.
201
     *
202
     * @param bool $without_cmd
203
     *
204
     * @return string
205
     */
206 14
    public function getText($without_cmd = false)
207
    {
208 14
        $text = $this->text;
209
210 14
        if ($without_cmd && $command = $this->getFullCommand()) {
211 6
            if (strlen($command) + 1 < strlen($text)) {
212 5
                $text = substr($text, strlen($command) + 1);
213
            } else {
214 3
                $text = '';
215
            }
216
        }
217
218 14
        return $text;
219
    }
220
221
    /**
222
     * Bot added in chat
223
     *
224
     * @return bool
225
     */
226
    public function botAddedInChat()
227
    {
228
        if (!empty($this->new_chat_member)) {
229
            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...
230
                return true;
231
            }
232
        }
233
234
        return false;
235
    }
236
237
    /**
238
     * Detect type based on properties.
239
     *
240
     * @return string|null
241
     */
242
    public function getType()
243
    {
244
        $types = [
245
            'text',
246
            'audio',
247
            'document',
248
            'photo',
249
            'sticker',
250
            'video',
251
            'voice',
252
            'contact',
253
            'location',
254
            'venue',
255
            'new_chat_member',
256
            'left_chat_member',
257
            'new_chat_title',
258
            'new_chat_photo',
259
            'delete_chat_photo',
260
            'group_chat_created',
261
            'supergroup_chat_created',
262
            'channel_chat_created',
263
            'migrate_to_chat_id',
264
            'migrate_from_chat_id',
265
            'pinned_message',
266
        ];
267
268
        foreach ($types as $type) {
269
            if ($this->getProperty($type)) {
270
                if ($type === 'text' && $this->getCommand()) {
271
                    return 'command';
272
                }
273
274
                return $type;
275
            }
276
        }
277
278
        return 'message';
279
    }
280
}
281