Completed
Push — develop ( 7b5bf5...5676b7 )
by Avtandil
13s
created

Entity   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 218
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 92.54%

Importance

Changes 0
Metric Value
wmc 32
lcom 1
cbo 0
dl 0
loc 218
ccs 62
cts 67
cp 0.9254
rs 9.6
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A toJson() 0 4 1
A __toString() 0 4 1
A subEntities() 0 4 1
A getProperty() 0 8 2
C __call() 0 30 8
C tryMention() 0 26 7
A __construct() 0 15 3
A assignMemberVariables() 0 6 2
A validate() 0 3 1
A escapeMarkdown() 0 8 1
B makePrettyObjectArray() 0 18 5
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 Longman\TelegramBot\TelegramLog;
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
28
{
29
    /**
30
     * Entity constructor.
31
     *
32
     * @todo Get rid of the $bot_username, it shouldn't be here!
33
     *
34
     * @param array  $data
35
     * @param string $bot_username
36
     *
37
     * @throws \Longman\TelegramBot\Exception\TelegramException
38
     */
39 76
    public function __construct($data, $bot_username = '')
40
    {
41
        //Make sure we're not raw_data inception-ing
42 76
        if (array_key_exists('raw_data', $data)) {
43 10
            if ($data['raw_data'] === null) {
44 10
                unset($data['raw_data']);
45
            }
46
        } else {
47 70
            $data['raw_data'] = $data;
48
        }
49
50 76
        $data['bot_username'] = $bot_username;
51 76
        $this->assignMemberVariables($data);
52 76
        $this->validate();
53 67
    }
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 76
    protected function assignMemberVariables(array $data)
81
    {
82 76
        foreach ($data as $key => $value) {
83 76
            $this->$key = $value;
84
        }
85 76
    }
86
87
    /**
88
     * Get the list of the properties that are themselves Entities
89
     *
90
     * @return array
91
     */
92 48
    protected function subEntities()
93
    {
94 48
        return [];
95
    }
96
97
    /**
98
     * Perform any special entity validation
99
     *
100
     * @throws \Longman\TelegramBot\Exception\TelegramException
101
     */
102 49
    protected function validate()
103
    {
104 49
    }
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 71
    public function getProperty($property, $default = null)
115
    {
116 71
        if (isset($this->$property)) {
117 66
            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 58
    public function __call($method, $args)
132
    {
133
        //Convert method to snake_case (which is the name of the property)
134 58
        $property_name = strtolower(ltrim(preg_replace('/[A-Z]/', '_$0', substr($method, 3)), '_'));
135
136 58
        $action = substr($method, 0, 3);
137 58
        if ($action === 'get') {
138 58
            $property = $this->getProperty($property_name);
139
140 58
            if ($property !== null) {
141
                //Get all sub-Entities of the current Entity
142 55
                $sub_entities = $this->subEntities();
143
144 55
                if (isset($sub_entities[$property_name])) {
145 10
                    return new $sub_entities[$property_name]($property, $this->getProperty('bot_username'));
146
                }
147
148 57
                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 7
    protected function makePrettyObjectArray($class, $property)
174
    {
175 7
        $new_objects = [];
176
177
        try {
178 7
            if ($objects = $this->getProperty($property)) {
179 1
                foreach ($objects as $object) {
180 1
                    if (!empty($object)) {
181 7
                        $new_objects[] = new $class($object);
182
                    }
183
                }
184
            }
185
        } catch (Exception $e) {
186
            $new_objects = [];
187
        }
188
189 7
        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 1
            $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