Complex classes like Request often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Request, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
79 | class Request |
||
80 | { |
||
81 | /** |
||
82 | * Telegram object |
||
83 | * |
||
84 | * @var \Longman\TelegramBot\Telegram |
||
85 | */ |
||
86 | private static $telegram; |
||
87 | |||
88 | /** |
||
89 | * URI of the Telegram API |
||
90 | * |
||
91 | * @var string |
||
92 | */ |
||
93 | private static $api_base_uri = 'https://api.telegram.org'; |
||
94 | |||
95 | /** |
||
96 | * Guzzle Client object |
||
97 | * |
||
98 | * @var \GuzzleHttp\Client |
||
99 | */ |
||
100 | private static $client; |
||
101 | |||
102 | /** |
||
103 | * Input value of the request |
||
104 | * |
||
105 | * @var string |
||
106 | */ |
||
107 | private static $input; |
||
108 | |||
109 | /** |
||
110 | * Request limiter |
||
111 | * |
||
112 | * @var boolean |
||
113 | */ |
||
114 | private static $limiter_enabled; |
||
115 | |||
116 | /** |
||
117 | * Request limiter's interval between checks |
||
118 | * |
||
119 | * @var float |
||
120 | */ |
||
121 | private static $limiter_interval; |
||
122 | |||
123 | /** |
||
124 | * Available actions to send |
||
125 | * |
||
126 | * This is basically the list of all methods listed on the official API documentation. |
||
127 | * |
||
128 | * @link https://core.telegram.org/bots/api |
||
129 | * |
||
130 | * @var array |
||
131 | */ |
||
132 | private static $actions = [ |
||
133 | 'getUpdates', |
||
134 | 'setWebhook', |
||
135 | 'deleteWebhook', |
||
136 | 'getWebhookInfo', |
||
137 | 'getMe', |
||
138 | 'sendMessage', |
||
139 | 'forwardMessage', |
||
140 | 'sendPhoto', |
||
141 | 'sendAudio', |
||
142 | 'sendDocument', |
||
143 | 'sendSticker', |
||
144 | 'sendVideo', |
||
145 | 'sendVoice', |
||
146 | 'sendVideoNote', |
||
147 | 'sendMediaGroup', |
||
148 | 'sendLocation', |
||
149 | 'editMessageLiveLocation', |
||
150 | 'stopMessageLiveLocation', |
||
151 | 'sendVenue', |
||
152 | 'sendContact', |
||
153 | 'sendChatAction', |
||
154 | 'getUserProfilePhotos', |
||
155 | 'getFile', |
||
156 | 'kickChatMember', |
||
157 | 'unbanChatMember', |
||
158 | 'restrictChatMember', |
||
159 | 'promoteChatMember', |
||
160 | 'exportChatInviteLink', |
||
161 | 'setChatPhoto', |
||
162 | 'deleteChatPhoto', |
||
163 | 'setChatTitle', |
||
164 | 'setChatDescription', |
||
165 | 'pinChatMessage', |
||
166 | 'unpinChatMessage', |
||
167 | 'leaveChat', |
||
168 | 'getChat', |
||
169 | 'getChatAdministrators', |
||
170 | 'getChatMembersCount', |
||
171 | 'getChatMember', |
||
172 | 'setChatStickerSet', |
||
173 | 'deleteChatStickerSet', |
||
174 | 'answerCallbackQuery', |
||
175 | 'answerInlineQuery', |
||
176 | 'editMessageText', |
||
177 | 'editMessageCaption', |
||
178 | 'editMessageReplyMarkup', |
||
179 | 'deleteMessage', |
||
180 | 'getStickerSet', |
||
181 | 'uploadStickerFile', |
||
182 | 'createNewStickerSet', |
||
183 | 'addStickerToSet', |
||
184 | 'setStickerPositionInSet', |
||
185 | 'deleteStickerFromSet', |
||
186 | 'sendInvoice', |
||
187 | 'answerShippingQuery', |
||
188 | 'answerPreCheckoutQuery', |
||
189 | ]; |
||
190 | |||
191 | /** |
||
192 | * Some methods need a dummy param due to certain cURL issues. |
||
193 | * |
||
194 | * @see Request::addDummyParamIfNecessary() |
||
195 | * |
||
196 | * @var array |
||
197 | */ |
||
198 | private static $actions_need_dummy_param = [ |
||
199 | 'deleteWebhook', |
||
200 | 'getWebhookInfo', |
||
201 | 'getMe', |
||
202 | ]; |
||
203 | |||
204 | /** |
||
205 | * Initialize |
||
206 | * |
||
207 | * @param \Longman\TelegramBot\Telegram $telegram |
||
208 | * |
||
209 | * @throws TelegramException |
||
210 | */ |
||
211 | 30 | public static function initialize(Telegram $telegram) |
|
212 | { |
||
213 | 30 | if (!($telegram instanceof Telegram)) { |
|
214 | throw new TelegramException('Invalid Telegram pointer!'); |
||
215 | } |
||
216 | |||
217 | 30 | self::$telegram = $telegram; |
|
218 | 30 | self::setClient(new Client(['base_uri' => self::$api_base_uri])); |
|
219 | 30 | } |
|
220 | |||
221 | /** |
||
222 | * Set a custom Guzzle HTTP Client object |
||
223 | * |
||
224 | * @param Client $client |
||
225 | * |
||
226 | * @throws TelegramException |
||
227 | */ |
||
228 | 30 | public static function setClient(Client $client) |
|
229 | { |
||
230 | 30 | if (!($client instanceof Client)) { |
|
231 | throw new TelegramException('Invalid GuzzleHttp\Client pointer!'); |
||
232 | } |
||
233 | |||
234 | 30 | self::$client = $client; |
|
235 | 30 | } |
|
236 | |||
237 | /** |
||
238 | * Set input from custom input or stdin and return it |
||
239 | * |
||
240 | * @return string |
||
241 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
242 | */ |
||
243 | public static function getInput() |
||
244 | { |
||
245 | // First check if a custom input has been set, else get the PHP input. |
||
246 | if (!($input = self::$telegram->getCustomInput())) { |
||
247 | $input = file_get_contents('php://input'); |
||
248 | } |
||
249 | |||
250 | // Make sure we have a string to work with. |
||
251 | if (!is_string($input)) { |
||
252 | throw new TelegramException('Input must be a string!'); |
||
253 | } |
||
254 | |||
255 | self::$input = $input; |
||
256 | |||
257 | TelegramLog::update(self::$input); |
||
258 | |||
259 | return self::$input; |
||
260 | } |
||
261 | |||
262 | /** |
||
263 | * Generate general fake server response |
||
264 | * |
||
265 | * @param array $data Data to add to fake response |
||
266 | * |
||
267 | * @return array Fake response data |
||
268 | */ |
||
269 | 1 | public static function generateGeneralFakeServerResponse(array $data = []) |
|
270 | { |
||
271 | //PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php |
||
272 | //Maybe this is not the best possible implementation |
||
273 | |||
274 | //No value set in $data ie testing setWebhook |
||
275 | //Provided $data['chat_id'] ie testing sendMessage |
||
276 | |||
277 | 1 | $fake_response = ['ok' => true]; // :) |
|
278 | |||
279 | 1 | if ($data === []) { |
|
280 | 1 | $fake_response['result'] = true; |
|
281 | } |
||
282 | |||
283 | //some data to let iniatilize the class method SendMessage |
||
284 | 1 | if (isset($data['chat_id'])) { |
|
285 | 1 | $data['message_id'] = '1234'; |
|
286 | 1 | $data['date'] = '1441378360'; |
|
287 | 1 | $data['from'] = [ |
|
288 | 'id' => 123456789, |
||
289 | 'first_name' => 'botname', |
||
290 | 'username' => 'namebot', |
||
291 | ]; |
||
292 | 1 | $data['chat'] = ['id' => $data['chat_id']]; |
|
293 | |||
294 | 1 | $fake_response['result'] = $data; |
|
295 | } |
||
296 | |||
297 | 1 | return $fake_response; |
|
298 | } |
||
299 | |||
300 | /** |
||
301 | * Properly set up the request params |
||
302 | * |
||
303 | * If any item of the array is a resource, reformat it to a multipart request. |
||
304 | * Else, just return the passed data as form params. |
||
305 | * |
||
306 | * @param array $data |
||
307 | * |
||
308 | * @return array |
||
309 | */ |
||
310 | private static function setUpRequestParams(array $data) |
||
311 | { |
||
312 | $has_resource = false; |
||
313 | $multipart = []; |
||
314 | |||
315 | // Convert any nested arrays into JSON strings. |
||
316 | array_walk($data, function (&$item) { |
||
317 | is_array($item) && $item = json_encode($item); |
||
318 | }); |
||
319 | |||
320 | //Reformat data array in multipart way if it contains a resource |
||
321 | foreach ($data as $key => $item) { |
||
322 | $has_resource |= (is_resource($item) || $item instanceof \GuzzleHttp\Psr7\Stream); |
||
323 | $multipart[] = ['name' => $key, 'contents' => $item]; |
||
324 | } |
||
325 | if ($has_resource) { |
||
326 | return ['multipart' => $multipart]; |
||
327 | } |
||
328 | |||
329 | return ['form_params' => $data]; |
||
330 | } |
||
331 | |||
332 | /** |
||
333 | * Execute HTTP Request |
||
334 | * |
||
335 | * @param string $action Action to execute |
||
336 | * @param array $data Data to attach to the execution |
||
337 | * |
||
338 | * @return string Result of the HTTP Request |
||
339 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
340 | */ |
||
341 | public static function execute($action, array $data = []) |
||
342 | { |
||
343 | //Fix so that the keyboard markup is a string, not an object |
||
344 | if (isset($data['reply_markup'])) { |
||
345 | $data['reply_markup'] = json_encode($data['reply_markup']); |
||
346 | } |
||
347 | |||
348 | $result = null; |
||
349 | $request_params = self::setUpRequestParams($data); |
||
350 | $request_params['debug'] = TelegramLog::getDebugLogTempStream(); |
||
351 | |||
352 | try { |
||
353 | $response = self::$client->post( |
||
354 | '/bot' . self::$telegram->getApiKey() . '/' . $action, |
||
355 | $request_params |
||
356 | ); |
||
357 | $result = (string) $response->getBody(); |
||
358 | |||
359 | //Logging getUpdates Update |
||
360 | if ($action === 'getUpdates') { |
||
361 | TelegramLog::update($result); |
||
362 | } |
||
363 | } catch (RequestException $e) { |
||
364 | $result = ($e->getResponse()) ? (string) $e->getResponse()->getBody() : ''; |
||
365 | } finally { |
||
366 | //Logging verbose debug output |
||
367 | TelegramLog::endDebugLogTempStream('Verbose HTTP Request output:' . PHP_EOL . '%s' . PHP_EOL); |
||
368 | } |
||
369 | |||
370 | return $result; |
||
371 | } |
||
372 | |||
373 | /** |
||
374 | * Download file |
||
375 | * |
||
376 | * @param \Longman\TelegramBot\Entities\File $file |
||
377 | * |
||
378 | * @return boolean |
||
379 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
380 | */ |
||
381 | public static function downloadFile(File $file) |
||
413 | |||
414 | /** |
||
415 | * Encode file |
||
416 | * |
||
417 | * @param string $file |
||
418 | * |
||
419 | * @return resource |
||
420 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
421 | */ |
||
422 | public static function encodeFile($file) |
||
431 | |||
432 | /** |
||
433 | * Send command |
||
434 | * |
||
435 | * @todo Fake response doesn't need json encoding? |
||
436 | * @todo Write debug entry on failure |
||
437 | * |
||
438 | * @param string $action |
||
439 | * @param array $data |
||
440 | * |
||
441 | * @return \Longman\TelegramBot\Entities\ServerResponse |
||
442 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
443 | */ |
||
444 | public static function send($action, array $data = []) |
||
477 | |||
478 | /** |
||
479 | * Add a dummy parameter if the passed action requires it. |
||
480 | * |
||
481 | * If a method doesn't require parameters, we need to add a dummy one anyway, |
||
482 | * because of some cURL version failed POST request without parameters. |
||
483 | * |
||
484 | * @link https://github.com/php-telegram-bot/core/pull/228 |
||
485 | * |
||
486 | * @todo Would be nice to find a better solution for this! |
||
487 | * |
||
488 | * @param string $action |
||
489 | * @param array $data |
||
490 | */ |
||
491 | protected static function addDummyParamIfNecessary($action, array &$data) |
||
498 | |||
499 | /** |
||
500 | * Make sure the data isn't empty, else throw an exception |
||
501 | * |
||
502 | * @param array $data |
||
503 | * |
||
504 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
505 | */ |
||
506 | private static function ensureNonEmptyData(array $data) |
||
512 | |||
513 | /** |
||
514 | * Make sure the action is valid, else throw an exception |
||
515 | * |
||
516 | * @param string $action |
||
517 | * |
||
518 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
519 | */ |
||
520 | private static function ensureValidAction($action) |
||
526 | |||
527 | /** |
||
528 | * Use this method to send text messages. On success, the sent Message is returned |
||
529 | * |
||
530 | * @link https://core.telegram.org/bots/api#sendmessage |
||
531 | * |
||
532 | * @param array $data |
||
533 | * |
||
534 | * @return \Longman\TelegramBot\Entities\ServerResponse |
||
535 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
536 | */ |
||
537 | public static function sendMessage(array $data) |
||
552 | |||
553 | /** |
||
554 | * Any statically called method should be relayed to the `send` method. |
||
555 | * |
||
556 | * @param string $action |
||
557 | * @param array $data |
||
558 | * |
||
559 | * @return \Longman\TelegramBot\Entities\ServerResponse |
||
560 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
561 | */ |
||
562 | public static function __callStatic($action, array $data) |
||
570 | |||
571 | /** |
||
572 | * Return an empty Server Response |
||
573 | * |
||
574 | * No request to telegram are sent, this function is used in commands that |
||
575 | * don't need to fire a message after execution |
||
576 | * |
||
577 | * @return \Longman\TelegramBot\Entities\ServerResponse |
||
578 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
579 | */ |
||
580 | public static function emptyResponse() |
||
584 | |||
585 | /** |
||
586 | * Send message to all active chats |
||
587 | * |
||
588 | * @param string $callback_function |
||
589 | * @param array $data |
||
590 | * @param array $select_chats_params |
||
591 | * |
||
592 | * @return array |
||
593 | * @throws TelegramException |
||
594 | */ |
||
595 | public static function sendToActiveChats( |
||
616 | |||
617 | /** |
||
618 | * Enable request limiter |
||
619 | * |
||
620 | * @param boolean $enable |
||
621 | * @param array $options |
||
622 | * |
||
623 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
624 | */ |
||
625 | public static function setLimiter($enable = true, array $options = []) |
||
642 | |||
643 | /** |
||
644 | * This functions delays API requests to prevent reaching Telegram API limits |
||
645 | * Can be disabled while in execution by 'Request::setLimiter(false)' |
||
646 | * |
||
647 | * @link https://core.telegram.org/bots/faq#my-bot-is-hitting-limits-how-do-i-avoid-this |
||
648 | * |
||
649 | * @param string $action |
||
650 | * @param array $data |
||
651 | * |
||
652 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
653 | */ |
||
654 | private static function limitTelegramRequests($action, array $data = []) |
||
712 | } |
||
713 |
Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.
For example, imagine you have a variable
$accountId
that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to theid
property of an instance of theAccount
class. This class holds a proper account, so the id value must no longer be false.Either this assignment is in error or a type check should be added for that assignment.