Completed
Push — develop ( 32ebf1...b1a895 )
by
unknown
15:09
created

Message::getPhoto()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 0
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 0
crap 6
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 null|PhotoSize[]
107
     */
108
    public function getPhoto()
109
    {
110
        $pretty_array = $this->makePrettyObjectArray(PhotoSize::class, 'photo');
111
112
        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|PhotoSize[]
122
     */
123
    public function getNewChatPhoto()
124
    {
125
        $pretty_array = $this->makePrettyObjectArray(PhotoSize::class, 'new_chat_photo');
126
127
        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|MessageEntity[]
137
     */
138
    public function getEntities()
139
    {
140
        $pretty_array = $this->makePrettyObjectArray(MessageEntity::class, 'entities');
141
142
        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
    public function getFullCommand()
151
    {
152
        $text = $this->getProperty('text');
153
        if (strpos($text, '/') === 0) {
154
            $no_EOL   = strtok($text, PHP_EOL);
155
            $no_space = strtok($text, ' ');
156
157
            //try to understand which separator \n or space divide /command from text
158
            return strlen($no_space) < strlen($no_EOL) ? $no_space : $no_EOL;
159
        }
160
161
        return null;
162
    }
163
164
    /**
165
     * Get command
166
     *
167
     * @return bool|string
168
     */
169
    public function getCommand()
170
    {
171
        $command = $this->getProperty('command');
172
        if (!empty($command)) {
173
            return $command;
174
        }
175
176
        $cmd = $this->getFullCommand();
177
178
        if (strpos($cmd, '/') === 0) {
179
            $cmd = substr($cmd, 1);
180
181
            //check if command is follow by botname
182
            $split_cmd = explode('@', $cmd);
183
            if (isset($split_cmd[1])) {
184
                //command is followed by name check if is addressed to me
185
                if (strtolower($split_cmd[1]) === strtolower($this->bot_name)) {
0 ignored issues
show
Bug introduced by
The property bot_name 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...
186
                    return $split_cmd[0];
187
                }
188
            } else {
189
                //command is not followed by name
190
                return $cmd;
191
            }
192
        }
193 18
194
        return false;
195
    }
196 18
197 18
    /**
198 2
     * For text messages, the actual UTF-8 text of the message, 0-4096 characters.
199
     *
200
     * @param bool $without_cmd
201 18
     *
202 18
     * @return string
203
     */
204
    public function getText($without_cmd = false)
205
    {
206
        $text = $this->getProperty('text');
207
208
        if ($without_cmd && $command = $this->getFullCommand()) {
209
            if (strlen($command) + 1 < strlen($text)) {
210
                $text = substr($text, strlen($command) + 1);
211 18
            } else {
212
                $text = '';
213 18
            }
214
        }
215 18
216
        return $text;
217 18
    }
218 18
219
    /**
220
     * Bot added in chat
221
     *
222 18
     * @return bool
223 18
     */
224 17
    public function botAddedInChat()
225
    {
226
        $member = $this->getNewChatMember();
227 18
228 18
        return $member !== null && $member->getUsername() === $this->getBotName();
0 ignored issues
show
Documentation Bug introduced by
The method getBotName does not exist on object<Longman\TelegramBot\Entities\Message>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
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