Entity   A
last analyzed

Complexity

Total Complexity 32

Size/Duplication

Total Lines 218
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 89.39%

Importance

Changes 0
Metric Value
wmc 32
c 0
b 0
f 0
lcom 1
cbo 0
dl 0
loc 218
ccs 59
cts 66
cp 0.8939
rs 9.6

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 15 3
A toJson() 0 4 1
A __toString() 0 4 1
A assignMemberVariables() 0 6 2
A subEntities() 0 4 1
A validate() 0 3 1
A getProperty() 0 8 2
C __call() 0 30 8
B makePrettyObjectArray() 0 18 5
A escapeMarkdown() 0 8 1
C tryMention() 0 26 7
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
use Exception;
14
use Longman\TelegramBot\Entities\InlineQuery\InlineEntity;
15
use ReflectionObject;
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 getBotName() Return the bot name passed to this entity
26
 */
27
abstract class Entity
28
{
29
    /**
30
     * Entity constructor.
31
     *
32
     * @todo Get rid of the $bot_name, it shouldn't be here!
33
     *
34
     * @param array  $data
35
     * @param string $bot_name
36
     *
37
     * @throws \Longman\TelegramBot\Exception\TelegramException
38
     */
39 81
    public function __construct($data, $bot_name = '')
40
    {
41
        //Make sure we're not raw_data inception-ing
42 81
        if (array_key_exists('raw_data', $data)) {
43 15
            if ($data['raw_data'] === null) {
44 15
                unset($data['raw_data']);
45
            }
46
        } else {
47 75
            $data['raw_data'] = $data;
48
        }
49
50 81
        $data['bot_name'] = $bot_name;
51 81
        $this->assignMemberVariables($data);
52 81
        $this->validate();
53 72
    }
54
55
    /**
56
     * Perform to json
57
     *
58
     * @return string
59
     */
60 1
    public function toJson()
61
    {
62 1
        return json_encode($this->getRawData());
63
    }
64
65
    /**
66
     * Perform to string
67
     *
68
     * @return string
69
     */
70
    public function __toString()
71
    {
72
        return $this->toJson();
73
    }
74
75
    /**
76
     * Helper to set member variables
77
     *
78
     * @param array $data
79
     */
80 81
    protected function assignMemberVariables(array $data)
81
    {
82 81
        foreach ($data as $key => $value) {
83 81
            $this->$key = $value;
84
        }
85 81
    }
86
87
    /**
88
     * Get the list of the properties that are themselves Entities
89
     *
90
     * @return array
91
     */
92 56
    protected function subEntities()
93
    {
94 56
        return [];
95
    }
96
97
    /**
98
     * Perform any special entity validation
99
     *
100
     * @throws \Longman\TelegramBot\Exception\TelegramException
101
     */
102 54
    protected function validate()
103
    {
104 54
    }
105
106
    /**
107
     * Get a property from the current Entity
108
     *
109
     * @param mixed $property
110
     * @param mixed $default
111
     *
112
     * @return mixed
113
     */
114 76
    public function getProperty($property, $default = null)
115
    {
116 76
        if (isset($this->$property)) {
117 71
            return $this->$property;
118
        }
119
120 43
        return $default;
121
    }
122
123
    /**
124
     * Return the variable for the called getter or magically set properties dynamically.
125
     *
126
     * @param $method
127
     * @param $args
128
     *
129
     * @return mixed|null
130
     */
131 63
    public function __call($method, $args)
132
    {
133
        //Convert method to snake_case (which is the name of the property)
134 63
        $property_name = ltrim(strtolower(preg_replace('/[A-Z]/', '_$0', substr($method, 3))), '_');
135
136 63
        $action = substr($method, 0, 3);
137 63
        if ($action === 'get') {
138 63
            $property = $this->getProperty($property_name);
139
140 63
            if ($property !== null) {
141
                //Get all sub-Entities of the current Entity
142 60
                $sub_entities = $this->subEntities();
143
144 60
                if (isset($sub_entities[$property_name])) {
145 16
                    return new $sub_entities[$property_name]($property, $this->getProperty('bot_name'));
146
                }
147
148 62
                return $property;
149
            }
150 3
        } elseif ($action === 'set') {
151
            // Limit setters to specific classes.
152 3
            if ($this instanceof InlineEntity || $this instanceof Keyboard || $this instanceof KeyboardButton) {
153 3
                $this->$property_name = $args[0];
154
155 3
                return $this;
156
            }
157
        }
158
159 29
        return null;
160
    }
161
162
    /**
163
     * Return an array of nice objects from an array of object arrays
164
     *
165
     * This method is used to generate pretty object arrays
166
     * mainly for PhotoSize and Entities object arrays.
167
     *
168
     * @param string $class
169
     * @param string $property
170
     *
171
     * @return array
172
     */
173 6
    protected function makePrettyObjectArray($class, $property)
174
    {
175 6
        $new_objects = [];
176
177
        try {
178 6
            if ($objects = $this->getProperty($property)) {
179
                foreach ($objects as $object) {
180
                    if (!empty($object)) {
181 6
                        $new_objects[] = new $class($object);
182
                    }
183
                }
184
            }
185
        } catch (Exception $e) {
186
            $new_objects = [];
187
        }
188
189 6
        return $new_objects;
190
    }
191
192
    /**
193
     * Escape markdown special characters
194
     *
195
     * @param string $string
196
     *
197
     * @return string
198
     */
199 1
    public function escapeMarkdown($string)
200
    {
201 1
        return str_replace(
202 1
            ['[', '`', '*', '_',],
203 1
            ['\[', '\`', '\*', '\_',],
204
            $string
205
        );
206
    }
207
208
    /**
209
     * Try to mention the user
210
     *
211
     * Mention the user with the username otherwise print first and last name
212
     * if the $escape_markdown argument is true special characters are escaped from the output
213
     *
214
     * @param bool $escape_markdown
215
     *
216
     * @return string|null
217
     */
218 3
    public function tryMention($escape_markdown = false)
219
    {
220
        //TryMention only makes sense for the User and Chat entity.
221 3
        if (!($this instanceof User || $this instanceof Chat)) {
222
            return null;
223
        }
224
225
        //Try with the username first...
226 3
        $name = $this->getProperty('username');
227 3
        $is_username = $name !== null;
228
229 3
        if ($name === null) {
230
            //...otherwise try with the names.
231 3
            $name      = $this->getProperty('first_name');
232 3
            $last_name = $this->getProperty('last_name');
233 3
            if ($last_name !== null) {
234 3
                $name .= ' ' . $last_name;
235
            }
236
        }
237
238 3
        if ($escape_markdown) {
239 1
            $name = $this->escapeMarkdown($name);
240
        }
241
242 3
        return ($is_username ? '@' : '') . $name;
243
    }
244
}
245