Completed
Pull Request — develop (#291)
by Armando
03:51
created

Message::getText()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 14
rs 9.2
ccs 7
cts 7
cp 1
cc 4
eloc 8
nc 3
nop 1
crap 4
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 array
107
     */
108 6
    public function getPhoto()
109
    {
110 6
        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 6
    public function getNewChatPhoto()
122
    {
123 6
        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 6
    public function getEntities()
135
    {
136 6
        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 6
    public function getFullCommand()
145
    {
146 6
        if (strpos($this->text, '/') === 0) {
147 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...
148 6
            $no_space = strtok($this->text, ' ');
149
150
            //try to understand which separator \n or space divide /command from text
151 6
            if (strlen($no_space) < strlen($no_EOL)) {
152 5
                return $no_space;
153
            } else {
154 3
                return $no_EOL;
155
            }
156
        } else {
157 1
            return null;
158
        }
159
    }
160
161
    /**
162
     * Get command
163
     *
164
     * @return bool|string
165
     */
166 1
    public function getCommand()
167
    {
168 1
        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 1
        $cmd = $this->getFullCommand();
173
174 1
        if (strpos($cmd, '/') === 0) {
175 1
            $cmd = substr($cmd, 1);
176
177
            //check if command is follow by botname
178 1
            $split_cmd = explode('@', $cmd);
179 1
            if (isset($split_cmd[1])) {
180
                //command is followed by name check if is addressed to me
181 1
                if (strtolower($split_cmd[1]) === strtolower($this->bot_name)) {
182 1
                    return $this->command = $split_cmd[0];
183
                }
184
            } else {
185
                //command is not followed by name
186 1
                return $this->command = $cmd;
187
            }
188
        }
189
190 1
        return false;
191
    }
192
193
    /**
194
     * For text messages, the actual UTF-8 text of the message, 0-4096 characters.
195
     *
196
     * @param bool $without_cmd
197
     *
198
     * @return string
199
     */
200 14
    public function getText($without_cmd = false)
201
    {
202 14
        $text = $this->text;
203
204 14
        if ($without_cmd && $command = $this->getFullCommand()) {
205 6
            if (strlen($command) + 1 < strlen($text)) {
206 5
                $text = substr($text, strlen($command) + 1);
207
            } else {
208 3
                $text = '';
209
            }
210
        }
211
212 14
        return $text;
213
    }
214
215
    /**
216
     * Bot added in chat
217
     *
218
     * @return bool
219
     */
220
    public function botAddedInChat()
221
    {
222
        if (!empty($this->new_chat_member)) {
223
            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
                return true;
225
            }
226
        }
227
228
        return false;
229
    }
230
231
    /**
232
     * Detect type based on properties.
233
     *
234
     * @return string|null
235
     */
236
    public function getType()
237
    {
238
        $types = [
239
            'text',
240
            'audio',
241
            'document',
242
            'photo',
243
            'sticker',
244
            'video',
245
            'voice',
246
            'contact',
247
            'location',
248
            'venue',
249
            'new_chat_member',
250
            'left_chat_member',
251
            'new_chat_title',
252
            'new_chat_photo',
253
            'delete_chat_photo',
254
            'group_chat_created',
255
            'supergroup_chat_created',
256
            'channel_chat_created',
257
            'migrate_to_chat_id',
258
            'migrate_from_chat_id',
259
            'pinned_message',
260
        ];
261
262
        foreach ($types as $type) {
263
            if ($this->getProperty($type)) {
264
                if ($type === 'text' && $this->getCommand()) {
265
                    return 'command';
266
                }
267
268
                return $type;
269
            }
270
        }
271
272
        return 'message';
273
    }
274
}
275