Passed
Pull Request — develop (#1390)
by
unknown
07:21
created

Entity::fixThumbnailRename()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 2
nop 1
dl 0
loc 3
ccs 1
cts 1
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
abstract class Entity implements \JsonSerializable
28
{
29
    public static $fixThumbnailRename = true;
30
    private $parameters = [];
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
     * Dynamically sets a parameter.
58
     *
59
     * @param string $name
60 2
     * @param        $value
61
     * @return void
62 2
     */
63
    public function __set(string $name, $value) : void {
64
        $this->parameters[$name] = $value;
65 2
    }
66 2
67
    /**
68 2
     * Gets a dynamic parameter.
69
     *
70
     * @param string $name
71
     * @return mixed|null
72
     */
73
    public function __get(string $name) {
74
        return $this->parameters[$name] ?? null;
75
    }
76 2
77
    /**
78 2
     * Return the data that should be serialized for Telegram.
79
     *
80
     * @return array
81
     */
82
    public function jsonSerialize(): array
83
    {
84
        $data = get_object_vars($this);
85
86
        // Delete unnecessary data
87
        unset($data['raw_data']);
88
        unset($data['bot_username']);
89
90
        return $data;
91
    }
92
93
    /**
94
     * Perform to json
95
     *
96 81
     * @return string
97
     */
98 81
    public function toJson(): string
99 81
    {
100
        return json_encode($this);
101
    }
102
103
    /**
104
     * Perform to string
105
     *
106
     * @return string
107
     */
108 34
    public function __toString()
109
    {
110 34
        return $this->toJson();
111
    }
112
113
    /**
114
     * Helper to set member variables
115
     *
116 57
     * @param array $data
117
     */
118 57
    protected function assignMemberVariables(array $data): void
119
    {
120
        foreach ($data as $key => $value) {
121
            $key = $this->fixThumbnailRename($key);
122
            $this->$key = $value;
123
        }
124
    }
125
126
    /**
127
     * Get the list of the properties that are themselves Entities
128 74
     *
129
     * @return array
130 74
     */
131
    protected function subEntities(): array
132
    {
133
        return [];
134
    }
135
136
    /**
137
     * Perform any special entity validation
138
     */
139
    protected function validate(): void
140
    {
141 61
    }
142
143
    /**
144 61
     * Get a property from the current Entity
145
     *
146 61
     * @param string $property
147 61
     * @param mixed  $default
148 61
     *
149
     * @return mixed
150 61
     */
151
    public function getProperty(string $property, $default = null)
152 57
    {
153
        return $this->$property ?? $default;
154 57
    }
155 15
156
    /**
157 15
     * Return the variable for the called getter or magically set properties dynamically.
158 1
     *
159
     * @param $method
160
     * @param $args
161 14
     *
162
     * @return mixed|null
163
     */
164 60
    public function __call($method, $args)
165
    {
166 4
        $method = $this->fixThumbnailRename($method);
167
168 4
        //Convert method to snake_case (which is the name of the property)
169 4
        $property_name = mb_strtolower(ltrim(preg_replace('/[A-Z]/', '_$0', substr($method, 3)), '_'));
170 4
        $property_name = $this->fixThumbnailRename($property_name);
171
172 4
        $action = substr($method, 0, 3);
173
        if ($action === 'get') {
174
            $property = $this->getProperty($property_name);
175
176 32
            if ($property !== null) {
177
                //Get all sub-Entities of the current Entity
178
                $sub_entities = $this->subEntities();
179
180
                if (isset($sub_entities[$property_name])) {
181
                    $class = $sub_entities[$property_name];
182
183
                    if (is_array($class)) {
184
                        return $this->makePrettyObjectArray(reset($class), $property_name);
185
                    }
186
187
                    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

187
                    return Factory::resolveEntityClass($class, $property, /** @scrutinizer ignore-type */ $this->getProperty('bot_username'));
Loading history...
188
                }
189
190 1
                return $property;
191
            }
192 1
        } elseif ($action === 'set') {
193 1
            // Limit setters to specific classes.
194
            if ($this instanceof InlineEntity || $this instanceof InputMedia || $this instanceof Keyboard || $this instanceof KeyboardButton) {
195 1
                $this->$property_name = $args[0];
196 1
                $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...
197 1
198
                return $this;
199
            }
200 1
        }
201
202
        return null;
203
    }
204
205
    /**
206
     * BC for renamed thumb -> thumbnail methods and fields
207
     *
208
     * @todo Remove after a few versions.
209
     *
210
     * @param string $name
211
     * @return string
212 2
     */
213
    protected function fixThumbnailRename(string $name): string
214 2
    {
215
        return self::$fixThumbnailRename ? preg_replace('/([Tt])humb(nail)?/', '$1humbnail', $name, -1, $count) : $name;
216
217
        /*if ($count) {
218
            // Notify user that there are still outdated method calls?
219
        }*/
220
    }
221
222
    /**
223
     * Return an array of nice objects from an array of object arrays
224
     *
225
     * This method is used to generate pretty object arrays
226
     * mainly for PhotoSize and Entities object arrays.
227
     *
228
     * @param string $class
229
     * @param string $property_name
230 1
     *
231
     * @return array
232 1
     */
233
    protected function makePrettyObjectArray(string $class, string $property_name): array
234
    {
235
        $objects      = [];
236
        $bot_username = $this->getProperty('bot_username');
237
238
        $properties = array_filter($this->getProperty($property_name) ?: []);
239
        foreach ($properties as $property) {
240
            $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

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