Passed
Pull Request — develop (#1395)
by Armando
15:20 queued 05:20
created

Entity::fixThumbnailRename()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 2
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of the TelegramBot package.
5
 *
6
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Longman\TelegramBot\Entities;
13
14
use Longman\TelegramBot\Entities\InlineQuery\InlineEntity;
15
use Longman\TelegramBot\Entities\InputMedia\InputMedia;
16
17
/**
18
 * Class Entity
19
 *
20
 * This is the base class for all entities.
21
 *
22
 * @link https://core.telegram.org/bots/api#available-types
23
 *
24
 * @method array  getRawData()     Get the raw data passed to this entity
25
 * @method string getBotUsername() Return the bot name passed to this entity
26
 */
27
#[\AllowDynamicProperties]
28
abstract class Entity implements \JsonSerializable
29
{
30
    public static $fixThumbnailRename = true;
31
32
    /**
33
     * Entity constructor.
34
     *
35
     * @todo Get rid of the $bot_username, it shouldn't be here!
36
     *
37
     * @param array  $data
38
     * @param string $bot_username
39 81
     */
40
    public function __construct(array $data, string $bot_username = '')
41
    {
42 81
        //Make sure we're not raw_data inception-ing
43 11
        if (array_key_exists('raw_data', $data)) {
44 11
            if ($data['raw_data'] === null) {
45
                unset($data['raw_data']);
46
            }
47 75
        } else {
48
            $data['raw_data'] = $data;
49
        }
50 81
51 81
        $data['bot_username'] = $bot_username;
52 81
        $this->assignMemberVariables($data);
53
        $this->validate();
54
    }
55
56
    /**
57
     * Return the data that should be serialized for Telegram.
58
     *
59
     * @return array
60 2
     */
61
    public function jsonSerialize(): array
62 2
    {
63
        $data = get_object_vars($this);
64
65 2
        // Delete unnecessary data
66 2
        unset($data['raw_data']);
67
        unset($data['bot_username']);
68 2
69
        return $data;
70
    }
71
72
    /**
73
     * Perform to json
74
     *
75
     * @return string
76 2
     */
77
    public function toJson(): string
78 2
    {
79
        return json_encode($this);
80
    }
81
82
    /**
83
     * Perform to string
84
     *
85
     * @return string
86
     */
87
    public function __toString()
88
    {
89
        return $this->toJson();
90
    }
91
92
    /**
93
     * Helper to set member variables
94
     *
95
     * @param array $data
96 81
     */
97
    protected function assignMemberVariables(array $data): void
98 81
    {
99 81
        foreach ($data as $key => $value) {
100
            $key = $this->fixThumbnailRename($key);
101
            $this->$key = $value;
102
        }
103
    }
104
105
    /**
106
     * Get the list of the properties that are themselves Entities
107
     *
108 34
     * @return array
109
     */
110 34
    protected function subEntities(): array
111
    {
112
        return [];
113
    }
114
115
    /**
116 57
     * Perform any special entity validation
117
     */
118 57
    protected function validate(): void
119
    {
120
    }
121
122
    /**
123
     * Get a property from the current Entity
124
     *
125
     * @param string $property
126
     * @param mixed  $default
127
     *
128 74
     * @return mixed
129
     */
130 74
    public function getProperty(string $property, $default = null)
131
    {
132
        return $this->$property ?? $default;
133
    }
134
135
    /**
136
     * Return the variable for the called getter or magically set properties dynamically.
137
     *
138
     * @param $method
139
     * @param $args
140
     *
141 61
     * @return mixed|null
142
     */
143
    public function __call($method, $args)
144 61
    {
145
        $method = $this->fixThumbnailRename($method);
146 61
147 61
        //Convert method to snake_case (which is the name of the property)
148 61
        $property_name = mb_strtolower(ltrim(preg_replace('/[A-Z]/', '_$0', substr($method, 3)), '_'));
149
        $property_name = $this->fixThumbnailRename($property_name);
150 61
151
        $action = substr($method, 0, 3);
152 57
        if ($action === 'get') {
153
            $property = $this->getProperty($property_name);
154 57
155 15
            if ($property !== null) {
156
                //Get all sub-Entities of the current Entity
157 15
                $sub_entities = $this->subEntities();
158 1
159
                if (isset($sub_entities[$property_name])) {
160
                    $class = $sub_entities[$property_name];
161 14
162
                    if (is_array($class)) {
163
                        return $this->makePrettyObjectArray(reset($class), $property_name);
164 60
                    }
165
166 4
                    return Factory::resolveEntityClass($class, $property, $this->getProperty('bot_username'));
0 ignored issues
show
Bug introduced by
It seems like $this->getProperty('bot_username') can also be of type null; however, parameter $bot_username of Longman\TelegramBot\Enti...y::resolveEntityClass() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

166
                    return Factory::resolveEntityClass($class, $property, /** @scrutinizer ignore-type */ $this->getProperty('bot_username'));
Loading history...
167
                }
168 4
169 4
                return $property;
170 4
            }
171
        } elseif ($action === 'set') {
172 4
            // Limit setters to specific classes.
173
            if ($this instanceof InlineEntity || $this instanceof InputMedia || $this instanceof Keyboard || $this instanceof KeyboardButton) {
174
                $this->$property_name = $args[0];
175
                $this->raw_data[$property_name] = $args[0];
0 ignored issues
show
Bug Best Practice introduced by
The property raw_data does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
176 32
177
                return $this;
178
            }
179
        }
180
181
        return null;
182
    }
183
184
    /**
185
     * BC for renamed thumb -> thumbnail methods and fields
186
     *
187
     * @todo Remove after a few versions.
188
     *
189
     * @param string $name
190 1
     * @return string
191
     */
192 1
    protected function fixThumbnailRename(string $name): string
193 1
    {
194
        return self::$fixThumbnailRename ? preg_replace('/([Tt])humb(nail)?/', '$1humbnail', $name, -1, $count) : $name;
195 1
196 1
        /*if ($count) {
197 1
            // Notify user that there are still outdated method calls?
198
        }*/
199
    }
200 1
201
    /**
202
     * Return an array of nice objects from an array of object arrays
203
     *
204
     * This method is used to generate pretty object arrays
205
     * mainly for PhotoSize and Entities object arrays.
206
     *
207
     * @param string $class
208
     * @param string $property_name
209
     *
210
     * @return array
211
     */
212 2
    protected function makePrettyObjectArray(string $class, string $property_name): array
213
    {
214 2
        $objects      = [];
215
        $bot_username = $this->getProperty('bot_username');
216
217
        $properties = array_filter($this->getProperty($property_name) ?: []);
218
        foreach ($properties as $property) {
219
            $objects[] = Factory::resolveEntityClass($class, $property, $bot_username);
0 ignored issues
show
Bug introduced by
It seems like $bot_username can also be of type null; however, parameter $bot_username of Longman\TelegramBot\Enti...y::resolveEntityClass() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

219
            $objects[] = Factory::resolveEntityClass($class, $property, /** @scrutinizer ignore-type */ $bot_username);
Loading history...
220
        }
221
222
        return $objects;
223
    }
224
225
    /**
226
     * Escape markdown (v1) special characters
227
     *
228
     * @see https://core.telegram.org/bots/api#markdown-style
229
     *
230 1
     * @param string $string
231
     *
232 1
     * @return string
233
     */
234
    public static function escapeMarkdown(string $string): string
235
    {
236
        return str_replace(
237
            ['[', '`', '*', '_',],
238
            ['\[', '\`', '\*', '\_',],
239
            $string
240
        );
241
    }
242
243
    /**
244
     * Escape markdown (v2) special characters
245
     *
246
     * @see https://core.telegram.org/bots/api#markdownv2-style
247
     *
248
     * @param string $string
249
     *
250
     * @return string
251 3
     */
252
    public static function escapeMarkdownV2(string $string): string
253
    {
254 3
        return str_replace(
255
            ['_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!'],
256
            ['\_', '\*', '\[', '\]', '\(', '\)', '\~', '\`', '\>', '\#', '\+', '\-', '\=', '\|', '\{', '\}', '\.', '\!'],
257
            $string
258
        );
259 3
    }
260 3
261
    /**
262 3
     * Try to mention the user
263
     *
264 3
     * Mention the user with the username otherwise print first and last name
265 3
     * if the $escape_markdown argument is true special characters are escaped from the output
266 3
     *
267 3
     * @todo What about MarkdownV2?
268
     *
269
     * @param bool $escape_markdown
270
     *
271 3
     * @return string
272 1
     */
273
    public function tryMention($escape_markdown = false): string
274
    {
275 3
        // TryMention only makes sense for the User and Chat entity.
276
        if (!($this instanceof User || $this instanceof Chat)) {
277
            return '';
278
        }
279
280
        //Try with the username first...
281
        $name        = $this->getProperty('username');
282
        $is_username = $name !== null;
283
284
        if ($name === null) {
285
            //...otherwise try with the names.
286
            $name      = $this->getProperty('first_name');
287
            $last_name = $this->getProperty('last_name');
288
            if ($last_name !== null) {
289
                $name .= ' ' . $last_name;
290
            }
291
        }
292
293
        if ($escape_markdown) {
294
            $name = self::escapeMarkdown($name);
295
        }
296
297
        return ($is_username ? '@' : '') . $name;
298
    }
299
}
300