Passed
Push — master ( 627c19...f3fe5e )
by Armando
03:09
created

Entity::jsonSerialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

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

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

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