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 |
||
83 | class Request |
||
84 | { |
||
85 | /** |
||
86 | * Telegram object |
||
87 | * |
||
88 | * @var \Longman\TelegramBot\Telegram |
||
89 | */ |
||
90 | private static $telegram; |
||
91 | |||
92 | /** |
||
93 | * URI of the Telegram API |
||
94 | * |
||
95 | * @var string |
||
96 | */ |
||
97 | private static $api_base_uri = 'https://api.telegram.org'; |
||
98 | |||
99 | /** |
||
100 | * Guzzle Client object |
||
101 | * |
||
102 | * @var \GuzzleHttp\Client |
||
103 | */ |
||
104 | private static $client; |
||
105 | |||
106 | /** |
||
107 | * Input value of the request |
||
108 | * |
||
109 | * @var string |
||
110 | */ |
||
111 | private static $input; |
||
112 | |||
113 | /** |
||
114 | * Request limiter |
||
115 | * |
||
116 | * @var boolean |
||
117 | */ |
||
118 | private static $limiter_enabled; |
||
119 | |||
120 | /** |
||
121 | * Request limiter's interval between checks |
||
122 | * |
||
123 | * @var float |
||
124 | */ |
||
125 | private static $limiter_interval; |
||
126 | |||
127 | /** |
||
128 | * Available actions to send |
||
129 | * |
||
130 | * This is basically the list of all methods listed on the official API documentation. |
||
131 | * |
||
132 | * @link https://core.telegram.org/bots/api |
||
133 | * |
||
134 | * @var array |
||
135 | */ |
||
136 | private static $actions = [ |
||
137 | 'getUpdates', |
||
138 | 'setWebhook', |
||
139 | 'deleteWebhook', |
||
140 | 'getWebhookInfo', |
||
141 | 'getMe', |
||
142 | 'sendMessage', |
||
143 | 'forwardMessage', |
||
144 | 'sendPhoto', |
||
145 | 'sendAudio', |
||
146 | 'sendDocument', |
||
147 | 'sendSticker', |
||
148 | 'sendVideo', |
||
149 | 'sendAnimation', |
||
150 | 'sendVoice', |
||
151 | 'sendVideoNote', |
||
152 | 'sendMediaGroup', |
||
153 | 'sendLocation', |
||
154 | 'editMessageLiveLocation', |
||
155 | 'stopMessageLiveLocation', |
||
156 | 'sendVenue', |
||
157 | 'sendContact', |
||
158 | 'sendChatAction', |
||
159 | 'getUserProfilePhotos', |
||
160 | 'getFile', |
||
161 | 'kickChatMember', |
||
162 | 'unbanChatMember', |
||
163 | 'restrictChatMember', |
||
164 | 'promoteChatMember', |
||
165 | 'exportChatInviteLink', |
||
166 | 'setChatPhoto', |
||
167 | 'deleteChatPhoto', |
||
168 | 'setChatTitle', |
||
169 | 'setChatDescription', |
||
170 | 'pinChatMessage', |
||
171 | 'unpinChatMessage', |
||
172 | 'leaveChat', |
||
173 | 'getChat', |
||
174 | 'getChatAdministrators', |
||
175 | 'getChatMembersCount', |
||
176 | 'getChatMember', |
||
177 | 'setChatStickerSet', |
||
178 | 'deleteChatStickerSet', |
||
179 | 'answerCallbackQuery', |
||
180 | 'answerInlineQuery', |
||
181 | 'editMessageText', |
||
182 | 'editMessageCaption', |
||
183 | 'editMessageReplyMarkup', |
||
184 | 'deleteMessage', |
||
185 | 'getStickerSet', |
||
186 | 'uploadStickerFile', |
||
187 | 'createNewStickerSet', |
||
188 | 'addStickerToSet', |
||
189 | 'setStickerPositionInSet', |
||
190 | 'deleteStickerFromSet', |
||
191 | 'sendInvoice', |
||
192 | 'answerShippingQuery', |
||
193 | 'answerPreCheckoutQuery', |
||
194 | 'sendGame', |
||
195 | 'setGameScore', |
||
196 | 'getGameHighScores', |
||
197 | ]; |
||
198 | |||
199 | /** |
||
200 | * Some methods need a dummy param due to certain cURL issues. |
||
201 | * |
||
202 | * @see Request::addDummyParamIfNecessary() |
||
203 | * |
||
204 | * @var array |
||
205 | */ |
||
206 | private static $actions_need_dummy_param = [ |
||
207 | 'deleteWebhook', |
||
208 | 'getWebhookInfo', |
||
209 | 'getMe', |
||
210 | ]; |
||
211 | |||
212 | /** |
||
213 | * Initialize |
||
214 | * |
||
215 | * @param \Longman\TelegramBot\Telegram $telegram |
||
216 | * |
||
217 | * @throws TelegramException |
||
218 | */ |
||
219 | 30 | public static function initialize(Telegram $telegram) |
|
220 | { |
||
221 | 30 | if (!($telegram instanceof Telegram)) { |
|
222 | throw new TelegramException('Invalid Telegram pointer!'); |
||
223 | } |
||
224 | |||
225 | 30 | self::$telegram = $telegram; |
|
226 | 30 | self::setClient(new Client(['base_uri' => self::$api_base_uri])); |
|
227 | 30 | } |
|
228 | |||
229 | /** |
||
230 | * Set a custom Guzzle HTTP Client object |
||
231 | * |
||
232 | * @param Client $client |
||
233 | * |
||
234 | * @throws TelegramException |
||
235 | */ |
||
236 | 30 | public static function setClient(Client $client) |
|
237 | { |
||
238 | 30 | if (!($client instanceof Client)) { |
|
239 | throw new TelegramException('Invalid GuzzleHttp\Client pointer!'); |
||
240 | } |
||
241 | |||
242 | 30 | self::$client = $client; |
|
243 | 30 | } |
|
244 | |||
245 | /** |
||
246 | * Set input from custom input or stdin and return it |
||
247 | * |
||
248 | * @return string |
||
249 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
250 | */ |
||
251 | public static function getInput() |
||
252 | { |
||
253 | // First check if a custom input has been set, else get the PHP input. |
||
254 | if (!($input = self::$telegram->getCustomInput())) { |
||
255 | $input = file_get_contents('php://input'); |
||
256 | } |
||
257 | |||
258 | // Make sure we have a string to work with. |
||
259 | if (!is_string($input)) { |
||
260 | throw new TelegramException('Input must be a string!'); |
||
261 | } |
||
262 | |||
263 | self::$input = $input; |
||
264 | |||
265 | TelegramLog::update(self::$input); |
||
266 | |||
267 | return self::$input; |
||
268 | } |
||
269 | |||
270 | /** |
||
271 | * Generate general fake server response |
||
272 | * |
||
273 | * @param array $data Data to add to fake response |
||
274 | * |
||
275 | * @return array Fake response data |
||
276 | */ |
||
277 | 1 | public static function generateGeneralFakeServerResponse(array $data = []) |
|
278 | { |
||
279 | //PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php |
||
280 | //Maybe this is not the best possible implementation |
||
281 | |||
282 | //No value set in $data ie testing setWebhook |
||
283 | //Provided $data['chat_id'] ie testing sendMessage |
||
284 | |||
285 | 1 | $fake_response = ['ok' => true]; // :) |
|
286 | |||
287 | 1 | if ($data === []) { |
|
288 | 1 | $fake_response['result'] = true; |
|
289 | } |
||
290 | |||
291 | //some data to let iniatilize the class method SendMessage |
||
292 | 1 | if (isset($data['chat_id'])) { |
|
293 | 1 | $data['message_id'] = '1234'; |
|
294 | 1 | $data['date'] = '1441378360'; |
|
295 | 1 | $data['from'] = [ |
|
296 | 'id' => 123456789, |
||
297 | 'first_name' => 'botname', |
||
298 | 'username' => 'namebot', |
||
299 | ]; |
||
300 | 1 | $data['chat'] = ['id' => $data['chat_id']]; |
|
301 | |||
302 | 1 | $fake_response['result'] = $data; |
|
303 | } |
||
304 | |||
305 | 1 | return $fake_response; |
|
306 | } |
||
307 | |||
308 | /** |
||
309 | * Properly set up the request params |
||
310 | * |
||
311 | * If any item of the array is a resource, reformat it to a multipart request. |
||
312 | * Else, just return the passed data as form params. |
||
313 | * |
||
314 | * @param array $data |
||
315 | * |
||
316 | * @return array |
||
317 | */ |
||
318 | private static function setUpRequestParams(array $data) |
||
319 | { |
||
320 | $has_resource = false; |
||
321 | $multipart = []; |
||
322 | |||
323 | // Convert any nested arrays into JSON strings. |
||
324 | array_walk($data, function (&$item) { |
||
325 | is_array($item) && $item = json_encode($item); |
||
326 | }); |
||
327 | |||
328 | //Reformat data array in multipart way if it contains a resource |
||
329 | foreach ($data as $key => $item) { |
||
330 | $has_resource |= (is_resource($item) || $item instanceof \GuzzleHttp\Psr7\Stream); |
||
331 | $multipart[] = ['name' => $key, 'contents' => $item]; |
||
332 | } |
||
333 | if ($has_resource) { |
||
334 | return ['multipart' => $multipart]; |
||
335 | } |
||
336 | |||
337 | return ['form_params' => $data]; |
||
338 | } |
||
339 | |||
340 | /** |
||
341 | * Execute HTTP Request |
||
342 | * |
||
343 | * @param string $action Action to execute |
||
344 | * @param array $data Data to attach to the execution |
||
345 | * |
||
346 | * @return string Result of the HTTP Request |
||
347 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
348 | */ |
||
349 | public static function execute($action, array $data = []) |
||
350 | { |
||
351 | //Fix so that the keyboard markup is a string, not an object |
||
352 | if (isset($data['reply_markup'])) { |
||
353 | $data['reply_markup'] = json_encode($data['reply_markup']); |
||
354 | } |
||
355 | |||
356 | $result = null; |
||
357 | $request_params = self::setUpRequestParams($data); |
||
358 | $request_params['debug'] = TelegramLog::getDebugLogTempStream(); |
||
359 | |||
360 | try { |
||
361 | $response = self::$client->post( |
||
362 | '/bot' . self::$telegram->getApiKey() . '/' . $action, |
||
363 | $request_params |
||
364 | ); |
||
365 | $result = (string) $response->getBody(); |
||
366 | |||
367 | //Logging getUpdates Update |
||
368 | if ($action === 'getUpdates') { |
||
369 | TelegramLog::update($result); |
||
370 | } |
||
371 | } catch (RequestException $e) { |
||
372 | $result = ($e->getResponse()) ? (string) $e->getResponse()->getBody() : ''; |
||
373 | } finally { |
||
374 | //Logging verbose debug output |
||
375 | TelegramLog::endDebugLogTempStream('Verbose HTTP Request output:' . PHP_EOL . '%s' . PHP_EOL); |
||
376 | } |
||
377 | |||
378 | return $result; |
||
379 | } |
||
380 | |||
381 | /** |
||
382 | * Download file |
||
383 | * |
||
384 | * @param \Longman\TelegramBot\Entities\File $file |
||
385 | * |
||
386 | * @return boolean |
||
387 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
388 | */ |
||
389 | public static function downloadFile(File $file) |
||
390 | { |
||
391 | if (empty($download_path = self::$telegram->getDownloadPath())) { |
||
392 | throw new TelegramException('Download path not set!'); |
||
393 | } |
||
394 | |||
395 | $tg_file_path = $file->getFilePath(); |
||
396 | $file_path = $download_path . '/' . $tg_file_path; |
||
397 | |||
398 | $file_dir = dirname($file_path); |
||
399 | //For safety reasons, first try to create the directory, then check that it exists. |
||
400 | //This is in case some other process has created the folder in the meantime. |
||
401 | if (!@mkdir($file_dir, 0755, true) && !is_dir($file_dir)) { |
||
402 | throw new TelegramException('Directory ' . $file_dir . ' can\'t be created'); |
||
403 | } |
||
404 | |||
405 | $debug_handle = TelegramLog::getDebugLogTempStream(); |
||
406 | |||
407 | try { |
||
408 | self::$client->get( |
||
409 | '/file/bot' . self::$telegram->getApiKey() . '/' . $tg_file_path, |
||
410 | ['debug' => $debug_handle, 'sink' => $file_path] |
||
411 | ); |
||
412 | |||
413 | return filesize($file_path) > 0; |
||
414 | } catch (RequestException $e) { |
||
415 | return ($e->getResponse()) ? (string) $e->getResponse()->getBody() : ''; |
||
416 | } finally { |
||
417 | //Logging verbose debug output |
||
418 | TelegramLog::endDebugLogTempStream('Verbose HTTP File Download Request output:' . PHP_EOL . '%s' . PHP_EOL); |
||
419 | } |
||
420 | } |
||
421 | |||
422 | /** |
||
423 | * Encode file |
||
424 | * |
||
425 | * @param string $file |
||
426 | * |
||
427 | * @return resource |
||
428 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
429 | */ |
||
430 | public static function encodeFile($file) |
||
431 | { |
||
432 | $fp = fopen($file, 'rb'); |
||
433 | if ($fp === false) { |
||
434 | throw new TelegramException('Cannot open "' . $file . '" for reading'); |
||
435 | } |
||
436 | |||
437 | return $fp; |
||
438 | } |
||
439 | |||
440 | /** |
||
441 | * Send command |
||
442 | * |
||
443 | * @todo Fake response doesn't need json encoding? |
||
444 | * @todo Write debug entry on failure |
||
445 | * |
||
446 | * @param string $action |
||
447 | * @param array $data |
||
448 | * |
||
449 | * @return \Longman\TelegramBot\Entities\ServerResponse |
||
450 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
451 | */ |
||
452 | public static function send($action, array $data = []) |
||
453 | { |
||
454 | self::ensureValidAction($action); |
||
455 | self::addDummyParamIfNecessary($action, $data); |
||
456 | |||
457 | $bot_username = self::$telegram->getBotUsername(); |
||
458 | |||
459 | if (defined('PHPUNIT_TESTSUITE')) { |
||
460 | $fake_response = self::generateGeneralFakeServerResponse($data); |
||
461 | |||
462 | return new ServerResponse($fake_response, $bot_username); |
||
463 | } |
||
464 | |||
465 | self::ensureNonEmptyData($data); |
||
466 | |||
467 | self::limitTelegramRequests($action, $data); |
||
468 | |||
469 | $raw_response = self::execute($action, $data); |
||
470 | $response = json_decode($raw_response, true); |
||
471 | |||
472 | if (null === $response) { |
||
473 | TelegramLog::debug($raw_response); |
||
474 | throw new TelegramException('Telegram returned an invalid response!'); |
||
475 | } |
||
476 | |||
477 | $response = new ServerResponse($response, $bot_username); |
||
478 | |||
479 | if (!$response->isOk() && $response->getErrorCode() === 401 && $response->getDescription() === 'Unauthorized') { |
||
480 | throw new InvalidBotTokenException(); |
||
481 | } |
||
482 | |||
483 | return $response; |
||
484 | } |
||
485 | |||
486 | /** |
||
487 | * Add a dummy parameter if the passed action requires it. |
||
488 | * |
||
489 | * If a method doesn't require parameters, we need to add a dummy one anyway, |
||
490 | * because of some cURL version failed POST request without parameters. |
||
491 | * |
||
492 | * @link https://github.com/php-telegram-bot/core/pull/228 |
||
493 | * |
||
494 | * @todo Would be nice to find a better solution for this! |
||
495 | * |
||
496 | * @param string $action |
||
497 | * @param array $data |
||
498 | */ |
||
499 | protected static function addDummyParamIfNecessary($action, array &$data) |
||
500 | { |
||
501 | if (in_array($action, self::$actions_need_dummy_param, true)) { |
||
502 | // Can be anything, using a single letter to minimise request size. |
||
503 | $data = ['d']; |
||
504 | } |
||
505 | } |
||
506 | |||
507 | /** |
||
508 | * Make sure the data isn't empty, else throw an exception |
||
509 | * |
||
510 | * @param array $data |
||
511 | * |
||
512 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
513 | */ |
||
514 | private static function ensureNonEmptyData(array $data) |
||
515 | { |
||
516 | if (count($data) === 0) { |
||
517 | throw new TelegramException('Data is empty!'); |
||
518 | } |
||
519 | } |
||
520 | |||
521 | /** |
||
522 | * Make sure the action is valid, else throw an exception |
||
523 | * |
||
524 | * @param string $action |
||
525 | * |
||
526 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
527 | */ |
||
528 | private static function ensureValidAction($action) |
||
529 | { |
||
530 | if (!in_array($action, self::$actions, true)) { |
||
531 | throw new TelegramException('The action "' . $action . '" doesn\'t exist!'); |
||
532 | } |
||
533 | } |
||
534 | |||
535 | /** |
||
536 | * Use this method to send text messages. On success, the sent Message is returned |
||
537 | * |
||
538 | * @link https://core.telegram.org/bots/api#sendmessage |
||
539 | * |
||
540 | * @param array $data |
||
541 | * |
||
542 | * @return \Longman\TelegramBot\Entities\ServerResponse |
||
543 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
544 | */ |
||
545 | public static function sendMessage(array $data) |
||
546 | { |
||
547 | $text = $data['text']; |
||
548 | |||
549 | do { |
||
550 | //Chop off and send the first message |
||
551 | $data['text'] = mb_substr($text, 0, 4096); |
||
552 | $response = self::send('sendMessage', $data); |
||
553 | |||
554 | //Prepare the next message |
||
555 | $text = mb_substr($text, 4096); |
||
556 | } while (mb_strlen($text, 'UTF-8') > 0); |
||
557 | |||
558 | return $response; |
||
559 | } |
||
560 | |||
561 | /** |
||
562 | * Any statically called method should be relayed to the `send` method. |
||
563 | * |
||
564 | * @param string $action |
||
565 | * @param array $data |
||
566 | * |
||
567 | * @return \Longman\TelegramBot\Entities\ServerResponse |
||
568 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
569 | */ |
||
570 | public static function __callStatic($action, array $data) |
||
571 | { |
||
572 | // Make sure to add the action being called as the first parameter to be passed. |
||
573 | array_unshift($data, $action); |
||
574 | |||
575 | // @todo Use splat operator for unpacking when we move to PHP 5.6+ |
||
576 | return call_user_func_array('static::send', $data); |
||
577 | } |
||
578 | |||
579 | /** |
||
580 | * Return an empty Server Response |
||
581 | * |
||
582 | * No request to telegram are sent, this function is used in commands that |
||
583 | * don't need to fire a message after execution |
||
584 | * |
||
585 | * @return \Longman\TelegramBot\Entities\ServerResponse |
||
586 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
587 | */ |
||
588 | public static function emptyResponse() |
||
589 | { |
||
590 | return new ServerResponse(['ok' => true, 'result' => true], null); |
||
591 | } |
||
592 | |||
593 | /** |
||
594 | * Send message to all active chats |
||
595 | * |
||
596 | * @param string $callback_function |
||
597 | * @param array $data |
||
598 | * @param array $select_chats_params |
||
599 | * |
||
600 | * @return array |
||
601 | * @throws TelegramException |
||
602 | */ |
||
603 | public static function sendToActiveChats( |
||
604 | $callback_function, |
||
605 | array $data, |
||
606 | array $select_chats_params |
||
607 | ) { |
||
608 | self::ensureValidAction($callback_function); |
||
609 | |||
610 | $chats = DB::selectChats($select_chats_params); |
||
611 | |||
612 | $results = []; |
||
613 | if (is_array($chats)) { |
||
614 | foreach ($chats as $row) { |
||
615 | $data['chat_id'] = $row['chat_id']; |
||
616 | $results[] = self::send($callback_function, $data); |
||
617 | } |
||
618 | } |
||
619 | |||
620 | return $results; |
||
621 | } |
||
622 | |||
623 | /** |
||
624 | * Enable request limiter |
||
625 | * |
||
626 | * @param boolean $enable |
||
627 | * @param array $options |
||
628 | * |
||
629 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
630 | */ |
||
631 | public static function setLimiter($enable = true, array $options = []) |
||
648 | |||
649 | /** |
||
650 | * This functions delays API requests to prevent reaching Telegram API limits |
||
651 | * Can be disabled while in execution by 'Request::setLimiter(false)' |
||
652 | * |
||
653 | * @link https://core.telegram.org/bots/faq#my-bot-is-hitting-limits-how-do-i-avoid-this |
||
654 | * |
||
655 | * @param string $action |
||
656 | * @param array $data |
||
657 | * |
||
658 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
659 | */ |
||
660 | private static function limitTelegramRequests($action, array $data = []) |
||
661 | { |
||
662 | if (self::$limiter_enabled) { |
||
663 | $limited_methods = [ |
||
664 | 'sendMessage', |
||
721 | } |
||
722 |
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.