GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

Entity::assignMemberVariables()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 4
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
30
31
    /**
32
     * Entity constructor.
33
     *
34
     * @todo Get rid of the $bot_username, it shouldn't be here!
35
     *
36
     * @param array  $data
37
     * @param string $bot_username
38
     */
39 73
    public function __construct(array $data, string $bot_username = '')
40
    {
41
        //Make sure we're not raw_data inception-ing
42 73
        if (array_key_exists('raw_data', $data)) {
43 9
            if ($data['raw_data'] === null) {
44 9
                unset($data['raw_data']);
45
            }
46
        } else {
47 67
            $data['raw_data'] = $data;
48
        }
49
50 73
        $data['bot_username'] = $bot_username;
51 73
        $this->assignMemberVariables($data);
52 73
        $this->validate();
53 64
    }
54
55
    /**
56
     * Return the data that should be serialized for Telegram.
57
     *
58
     * @return array
59
     */
60 1
    public function jsonSerialize(): array
61
    {
62 1
        return $this->getRawData();
63
    }
64
65
    /**
66
     * Perform to json
67
     *
68
     * @return string
69
     */
70
    public function toJson(): string
71
    {
72
        return json_encode($this);
73
    }
74
75
    /**
76
     * Perform to string
77
     *
78
     * @return string
79
     */
80 73
    public function __toString()
81
    {
82 73
        return $this->toJson();
83 73
    }
84
85 73
    /**
86
     * Helper to set member variables
87
     *
88
     * @param array $data
89
     */
90
    protected function assignMemberVariables(array $data): void
91
    {
92 46
        foreach ($data as $key => $value) {
93
            $this->$key = $value;
94 46
        }
95
    }
96
97
    /**
98
     * Get the list of the properties that are themselves Entities
99
     *
100
     * @return array
101
     */
102 48
    protected function subEntities(): array
103
    {
104 48
        return [];
105
    }
106
107
    /**
108
     * Perform any special entity validation
109
     */
110
    protected function validate(): void
111
    {
112
    }
113
114 68
    /**
115
     * Get a property from the current Entity
116 68
     *
117 63
     * @param string $property
118
     * @param mixed  $default
119
     *
120 41
     * @return mixed
121
     */
122
    public function getProperty(string $property, $default = null)
123
    {
124
        return $this->$property ?? $default;
125
    }
126
127
    /**
128
     * Return the variable for the called getter or magically set properties dynamically.
129
     *
130
     * @param $method
131 56
     * @param $args
132
     *
133
     * @return mixed|null
134 56
     */
135
    public function __call($method, $args)
136 56
    {
137 56
        //Convert method to snake_case (which is the name of the property)
138 56
        $property_name = mb_strtolower(ltrim(preg_replace('/[A-Z]/', '_$0', substr($method, 3)), '_'));
139
140 56
        $action = substr($method, 0, 3);
141
        if ($action === 'get') {
142 53
            $property = $this->getProperty($property_name);
143
144 53
            if ($property !== null) {
145 10
                //Get all sub-Entities of the current Entity
146
                $sub_entities = $this->subEntities();
147
148 55
                if (isset($sub_entities[$property_name])) {
149
                    $class = $sub_entities[$property_name];
150 3
151
                    if (is_array($class)) {
152 3
                        return $this->makePrettyObjectArray(reset($class), $property_name);
153 3
                    }
154
155 3
                    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

155
                    return Factory::resolveEntityClass($class, $property, /** @scrutinizer ignore-type */ $this->getProperty('bot_username'));
Loading history...
156
                }
157
158
                return $property;
159 28
            }
160
        } elseif ($action === 'set') {
161
            // Limit setters to specific classes.
162
            if ($this instanceof InlineEntity || $this instanceof InputMedia || $this instanceof Keyboard || $this instanceof KeyboardButton) {
163
                $this->$property_name = $args[0];
164
                $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...
165
166
                return $this;
167
            }
168
        }
169
170
        return null;
171
    }
172
173 6
    /**
174
     * Return an array of nice objects from an array of object arrays
175 6
     *
176
     * This method is used to generate pretty object arrays
177
     * mainly for PhotoSize and Entities object arrays.
178 6
     *
179
     * @param string $class
180
     * @param string $property_name
181 6
     *
182
     * @return array
183
     */
184
    protected function makePrettyObjectArray(string $class, string $property_name): array
185
    {
186
        $objects      = [];
187
        $bot_username = $this->getProperty('bot_username');
188
189 6
        $properties = array_filter($this->getProperty($property_name) ?: []);
190
        foreach ($properties as $property) {
191
            $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

191
            $objects[] = Factory::resolveEntityClass($class, $property, /** @scrutinizer ignore-type */ $bot_username);
Loading history...
192
        }
193
194
        return $objects;
195
    }
196
197
    /**
198
     * Escape markdown (v1) special characters
199 1
     *
200
     * @see https://core.telegram.org/bots/api#markdown-style
201 1
     *
202 1
     * @param string $string
203 1
     *
204 1
     * @return string
205
     */
206
    public static function escapeMarkdown(string $string): string
207
    {
208
        return str_replace(
209
            ['[', '`', '*', '_',],
210
            ['\[', '\`', '\*', '\_',],
211
            $string
212
        );
213
    }
214
215
    /**
216
     * Escape markdown (v2) special characters
217
     *
218 3
     * @see https://core.telegram.org/bots/api#markdownv2-style
219
     *
220
     * @param string $string
221 3
     *
222
     * @return string
223
     */
224
    public static function escapeMarkdownV2(string $string): string
225
    {
226 3
        return str_replace(
227 3
            ['_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!'],
228
            ['\_', '\*', '\[', '\]', '\(', '\)', '\~', '\`', '\>', '\#', '\+', '\-', '\=', '\|', '\{', '\}', '\.', '\!'],
229 3
            $string
230
        );
231 3
    }
232 3
233 3
    /**
234 3
     * Try to mention the user
235
     *
236
     * Mention the user with the username otherwise print first and last name
237
     * if the $escape_markdown argument is true special characters are escaped from the output
238 3
     *
239 1
     * @todo What about MarkdownV2?
240
     *
241
     * @param bool $escape_markdown
242 3
     *
243
     * @return string
244
     */
245
    public function tryMention($escape_markdown = false): string
246
    {
247
        // TryMention only makes sense for the User and Chat entity.
248
        if (!($this instanceof User || $this instanceof Chat)) {
249
            return '';
250
        }
251
252
        //Try with the username first...
253
        $name        = $this->getProperty('username');
254
        $is_username = $name !== null;
255
256
        if ($name === null) {
257
            //...otherwise try with the names.
258
            $name      = $this->getProperty('first_name');
259
            $last_name = $this->getProperty('last_name');
260
            if ($last_name !== null) {
261
                $name .= ' ' . $last_name;
262
            }
263
        }
264
265
        if ($escape_markdown) {
266
            $name = self::escapeMarkdown($name);
267
        }
268
269
        return ($is_username ? '@' : '') . $name;
270
    }
271
}
272