| Total Complexity | 91 |
| Total Lines | 805 |
| Duplicated Lines | 0 % |
| Changes | 42 | ||
| Bugs | 3 | Features | 1 |
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.
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 |
||
| 103 | class Request |
||
| 104 | { |
||
| 105 | /** |
||
| 106 | * Telegram object |
||
| 107 | * |
||
| 108 | * @var Telegram |
||
| 109 | */ |
||
| 110 | private static $telegram; |
||
| 111 | |||
| 112 | /** |
||
| 113 | * URI of the Telegram API |
||
| 114 | * |
||
| 115 | * @var string |
||
| 116 | */ |
||
| 117 | private static $api_base_uri = 'https://api.telegram.org'; |
||
| 118 | |||
| 119 | /** |
||
| 120 | * URI of the Telegram API for downloading files (relative to $api_base_url or absolute) |
||
| 121 | * |
||
| 122 | * @var string |
||
| 123 | */ |
||
| 124 | private static $api_base_download_uri = '/file/bot{API_KEY}'; |
||
| 125 | |||
| 126 | /** |
||
| 127 | * Guzzle Client object |
||
| 128 | * |
||
| 129 | * @var ClientInterface |
||
| 130 | */ |
||
| 131 | private static $client; |
||
| 132 | |||
| 133 | /** |
||
| 134 | * Request limiter |
||
| 135 | * |
||
| 136 | * @var bool |
||
| 137 | */ |
||
| 138 | private static $limiter_enabled; |
||
| 139 | |||
| 140 | /** |
||
| 141 | * Request limiter's interval between checks |
||
| 142 | * |
||
| 143 | * @var float |
||
| 144 | */ |
||
| 145 | private static $limiter_interval; |
||
| 146 | |||
| 147 | /** |
||
| 148 | * The current action that is being executed |
||
| 149 | * |
||
| 150 | * @var string |
||
| 151 | */ |
||
| 152 | private static $current_action = ''; |
||
| 153 | |||
| 154 | /** |
||
| 155 | * Available actions to send |
||
| 156 | * |
||
| 157 | * This is basically the list of all methods listed on the official API documentation. |
||
| 158 | * |
||
| 159 | * @link https://core.telegram.org/bots/api |
||
| 160 | * |
||
| 161 | * @var array |
||
| 162 | */ |
||
| 163 | private static $actions = [ |
||
| 164 | 'getUpdates', |
||
| 165 | 'setWebhook', |
||
| 166 | 'deleteWebhook', |
||
| 167 | 'getWebhookInfo', |
||
| 168 | 'getMe', |
||
| 169 | 'logOut', |
||
| 170 | 'close', |
||
| 171 | 'sendMessage', |
||
| 172 | 'forwardMessage', |
||
| 173 | 'copyMessage', |
||
| 174 | 'sendPhoto', |
||
| 175 | 'sendAudio', |
||
| 176 | 'sendDocument', |
||
| 177 | 'sendSticker', |
||
| 178 | 'sendVideo', |
||
| 179 | 'sendAnimation', |
||
| 180 | 'sendVoice', |
||
| 181 | 'sendVideoNote', |
||
| 182 | 'sendMediaGroup', |
||
| 183 | 'sendLocation', |
||
| 184 | 'editMessageLiveLocation', |
||
| 185 | 'stopMessageLiveLocation', |
||
| 186 | 'sendVenue', |
||
| 187 | 'sendContact', |
||
| 188 | 'sendPoll', |
||
| 189 | 'sendDice', |
||
| 190 | 'sendChatAction', |
||
| 191 | 'getUserProfilePhotos', |
||
| 192 | 'getFile', |
||
| 193 | 'kickChatMember', |
||
| 194 | 'unbanChatMember', |
||
| 195 | 'restrictChatMember', |
||
| 196 | 'promoteChatMember', |
||
| 197 | 'setChatAdministratorCustomTitle', |
||
| 198 | 'setChatPermissions', |
||
| 199 | 'exportChatInviteLink', |
||
| 200 | 'setChatPhoto', |
||
| 201 | 'deleteChatPhoto', |
||
| 202 | 'setChatTitle', |
||
| 203 | 'setChatDescription', |
||
| 204 | 'pinChatMessage', |
||
| 205 | 'unpinChatMessage', |
||
| 206 | 'unpinAllChatMessages', |
||
| 207 | 'leaveChat', |
||
| 208 | 'getChat', |
||
| 209 | 'getChatAdministrators', |
||
| 210 | 'getChatMembersCount', |
||
| 211 | 'getChatMember', |
||
| 212 | 'setChatStickerSet', |
||
| 213 | 'deleteChatStickerSet', |
||
| 214 | 'answerCallbackQuery', |
||
| 215 | 'answerInlineQuery', |
||
| 216 | 'setMyCommands', |
||
| 217 | 'getMyCommands', |
||
| 218 | 'editMessageText', |
||
| 219 | 'editMessageCaption', |
||
| 220 | 'editMessageMedia', |
||
| 221 | 'editMessageReplyMarkup', |
||
| 222 | 'stopPoll', |
||
| 223 | 'deleteMessage', |
||
| 224 | 'getStickerSet', |
||
| 225 | 'uploadStickerFile', |
||
| 226 | 'createNewStickerSet', |
||
| 227 | 'addStickerToSet', |
||
| 228 | 'setStickerPositionInSet', |
||
| 229 | 'deleteStickerFromSet', |
||
| 230 | 'setStickerSetThumb', |
||
| 231 | 'sendInvoice', |
||
| 232 | 'answerShippingQuery', |
||
| 233 | 'answerPreCheckoutQuery', |
||
| 234 | 'setPassportDataErrors', |
||
| 235 | 'sendGame', |
||
| 236 | 'setGameScore', |
||
| 237 | 'getGameHighScores', |
||
| 238 | ]; |
||
| 239 | |||
| 240 | /** |
||
| 241 | * Some methods need a dummy param due to certain cURL issues. |
||
| 242 | * |
||
| 243 | * @see Request::addDummyParamIfNecessary() |
||
| 244 | * |
||
| 245 | * @var array |
||
| 246 | */ |
||
| 247 | private static $actions_need_dummy_param = [ |
||
| 248 | 'deleteWebhook', |
||
| 249 | 'getWebhookInfo', |
||
| 250 | 'getMe', |
||
| 251 | 'logOut', |
||
| 252 | 'close', |
||
| 253 | 'getMyCommands', |
||
| 254 | ]; |
||
| 255 | |||
| 256 | /** |
||
| 257 | * Available fields for InputFile helper |
||
| 258 | * |
||
| 259 | * This is basically the list of all fields that allow InputFile objects |
||
| 260 | * for which input can be simplified by providing local path directly as string. |
||
| 261 | * |
||
| 262 | * @var array |
||
| 263 | */ |
||
| 264 | private static $input_file_fields = [ |
||
| 265 | 'setWebhook' => ['certificate'], |
||
| 266 | 'sendPhoto' => ['photo'], |
||
| 267 | 'sendAudio' => ['audio', 'thumb'], |
||
| 268 | 'sendDocument' => ['document', 'thumb'], |
||
| 269 | 'sendVideo' => ['video', 'thumb'], |
||
| 270 | 'sendAnimation' => ['animation', 'thumb'], |
||
| 271 | 'sendVoice' => ['voice', 'thumb'], |
||
| 272 | 'sendVideoNote' => ['video_note', 'thumb'], |
||
| 273 | 'setChatPhoto' => ['photo'], |
||
| 274 | 'sendSticker' => ['sticker'], |
||
| 275 | 'uploadStickerFile' => ['png_sticker'], |
||
| 276 | 'createNewStickerSet' => ['png_sticker', 'tgs_sticker'], |
||
| 277 | 'addStickerToSet' => ['png_sticker', 'tgs_sticker'], |
||
| 278 | 'setStickerSetThumb' => ['thumb'], |
||
| 279 | ]; |
||
| 280 | |||
| 281 | /** |
||
| 282 | * Initialize |
||
| 283 | * |
||
| 284 | * @param Telegram $telegram |
||
| 285 | */ |
||
| 286 | public static function initialize(Telegram $telegram): void |
||
| 287 | { |
||
| 288 | self::$telegram = $telegram; |
||
| 289 | self::setClient(self::$client ?: new Client(['base_uri' => self::$api_base_uri])); |
||
| 290 | } |
||
| 291 | |||
| 292 | /** |
||
| 293 | * Set a custom Guzzle HTTP Client object |
||
| 294 | * |
||
| 295 | * @param ClientInterface $client |
||
| 296 | */ |
||
| 297 | public static function setClient(ClientInterface $client): void |
||
| 298 | { |
||
| 299 | self::$client = $client; |
||
| 300 | } |
||
| 301 | |||
| 302 | /** |
||
| 303 | * Set a custom Bot API URL |
||
| 304 | * |
||
| 305 | * @param string $api_base_uri |
||
| 306 | * @param string $api_base_download_uri |
||
| 307 | */ |
||
| 308 | public static function setCustomBotApiUri(string $api_base_uri, string $api_base_download_uri = ''): void |
||
| 309 | { |
||
| 310 | self::$api_base_uri = $api_base_uri; |
||
| 311 | if ($api_base_download_uri !== '') { |
||
| 312 | self::$api_base_download_uri = $api_base_download_uri; |
||
| 313 | } |
||
| 314 | } |
||
| 315 | |||
| 316 | /** |
||
| 317 | * Get input from custom input or stdin and return it |
||
| 318 | * |
||
| 319 | * @return string |
||
| 320 | */ |
||
| 321 | public static function getInput(): string |
||
| 322 | { |
||
| 323 | // First check if a custom input has been set, else get the PHP input. |
||
| 324 | return self::$telegram->getCustomInput() |
||
| 325 | ?: file_get_contents('php://input'); |
||
| 326 | } |
||
| 327 | |||
| 328 | /** |
||
| 329 | * Generate general fake server response |
||
| 330 | * |
||
| 331 | * @param array $data Data to add to fake response |
||
| 332 | * |
||
| 333 | * @return array Fake response data |
||
| 334 | */ |
||
| 335 | public static function generateGeneralFakeServerResponse(array $data = []): array |
||
| 336 | { |
||
| 337 | //PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php |
||
| 338 | //Maybe this is not the best possible implementation |
||
| 339 | |||
| 340 | //No value set in $data ie testing setWebhook |
||
| 341 | //Provided $data['chat_id'] ie testing sendMessage |
||
| 342 | |||
| 343 | $fake_response = ['ok' => true]; // :) |
||
| 344 | |||
| 345 | if ($data === []) { |
||
| 346 | $fake_response['result'] = true; |
||
| 347 | } |
||
| 348 | |||
| 349 | //some data to initialize the class method SendMessage |
||
| 350 | if (isset($data['chat_id'])) { |
||
| 351 | $data['message_id'] = '1234'; |
||
| 352 | $data['date'] = '1441378360'; |
||
| 353 | $data['from'] = [ |
||
| 354 | 'id' => 123456789, |
||
| 355 | 'first_name' => 'botname', |
||
| 356 | 'username' => 'namebot', |
||
| 357 | ]; |
||
| 358 | $data['chat'] = ['id' => $data['chat_id']]; |
||
| 359 | |||
| 360 | $fake_response['result'] = $data; |
||
| 361 | } |
||
| 362 | |||
| 363 | return $fake_response; |
||
| 364 | } |
||
| 365 | |||
| 366 | /** |
||
| 367 | * Properly set up the request params |
||
| 368 | * |
||
| 369 | * If any item of the array is a resource, reformat it to a multipart request. |
||
| 370 | * Else, just return the passed data as form params. |
||
| 371 | * |
||
| 372 | * @param array $data |
||
| 373 | * |
||
| 374 | * @return array |
||
| 375 | * @throws TelegramException |
||
| 376 | */ |
||
| 377 | private static function setUpRequestParams(array $data): array |
||
| 378 | { |
||
| 379 | $has_resource = false; |
||
| 380 | $multipart = []; |
||
| 381 | |||
| 382 | foreach ($data as $key => &$item) { |
||
| 383 | if ($key === 'media') { |
||
| 384 | // Magical media input helper. |
||
| 385 | $item = self::mediaInputHelper($item, $has_resource, $multipart); |
||
| 386 | } elseif (array_key_exists(self::$current_action, self::$input_file_fields) && in_array($key, self::$input_file_fields[self::$current_action], true)) { |
||
| 387 | // Allow absolute paths to local files. |
||
| 388 | if (is_string($item) && file_exists($item)) { |
||
| 389 | $item = new Stream(self::encodeFile($item)); |
||
| 390 | } |
||
| 391 | } elseif (is_array($item) || is_object($item)) { |
||
| 392 | // Convert any nested arrays or objects into JSON strings. |
||
| 393 | $item = json_encode($item); |
||
| 394 | } |
||
| 395 | |||
| 396 | // Reformat data array in multipart way if it contains a resource |
||
| 397 | $has_resource = $has_resource || is_resource($item) || $item instanceof Stream; |
||
| 398 | $multipart[] = ['name' => $key, 'contents' => $item]; |
||
| 399 | } |
||
| 400 | unset($item); |
||
| 401 | |||
| 402 | if ($has_resource) { |
||
| 403 | return ['multipart' => $multipart]; |
||
| 404 | } |
||
| 405 | |||
| 406 | return ['form_params' => $data]; |
||
| 407 | } |
||
| 408 | |||
| 409 | /** |
||
| 410 | * Magical input media helper to simplify passing media. |
||
| 411 | * |
||
| 412 | * This allows the following: |
||
| 413 | * Request::editMessageMedia([ |
||
| 414 | * ... |
||
| 415 | * 'media' => new InputMediaPhoto([ |
||
| 416 | * 'caption' => 'Caption!', |
||
| 417 | * 'media' => Request::encodeFile($local_photo), |
||
| 418 | * ]), |
||
| 419 | * ]); |
||
| 420 | * and |
||
| 421 | * Request::sendMediaGroup([ |
||
| 422 | * 'media' => [ |
||
| 423 | * new InputMediaPhoto(['media' => Request::encodeFile($local_photo_1)]), |
||
| 424 | * new InputMediaPhoto(['media' => Request::encodeFile($local_photo_2)]), |
||
| 425 | * new InputMediaVideo(['media' => Request::encodeFile($local_video_1)]), |
||
| 426 | * ], |
||
| 427 | * ]); |
||
| 428 | * and even |
||
| 429 | * Request::sendMediaGroup([ |
||
| 430 | * 'media' => [ |
||
| 431 | * new InputMediaPhoto(['media' => $local_photo_1]), |
||
| 432 | * new InputMediaPhoto(['media' => $local_photo_2]), |
||
| 433 | * new InputMediaVideo(['media' => $local_video_1]), |
||
| 434 | * ], |
||
| 435 | * ]); |
||
| 436 | * |
||
| 437 | * @param mixed $item |
||
| 438 | * @param bool $has_resource |
||
| 439 | * @param array $multipart |
||
| 440 | * |
||
| 441 | * @return mixed |
||
| 442 | * @throws TelegramException |
||
| 443 | */ |
||
| 444 | private static function mediaInputHelper($item, bool &$has_resource, array &$multipart) |
||
| 445 | { |
||
| 446 | $was_array = is_array($item); |
||
| 447 | $was_array || $item = [$item]; |
||
| 448 | |||
| 449 | /** @var InputMedia|null $media_item */ |
||
| 450 | foreach ($item as $media_item) { |
||
| 451 | if (!($media_item instanceof InputMedia)) { |
||
| 452 | continue; |
||
| 453 | } |
||
| 454 | |||
| 455 | // Make a list of all possible media that can be handled by the helper. |
||
| 456 | $possible_medias = array_filter([ |
||
| 457 | 'media' => $media_item->getMedia(), |
||
|
|
|||
| 458 | 'thumb' => $media_item->getThumb(), |
||
| 459 | ]); |
||
| 460 | |||
| 461 | foreach ($possible_medias as $type => $media) { |
||
| 462 | // Allow absolute paths to local files. |
||
| 463 | if (is_string($media) && strpos($media, 'attach://') !== 0 && file_exists($media)) { |
||
| 464 | $media = new Stream(self::encodeFile($media)); |
||
| 465 | } |
||
| 466 | |||
| 467 | if (is_resource($media) || $media instanceof Stream) { |
||
| 468 | $has_resource = true; |
||
| 469 | $unique_key = uniqid($type . '_', false); |
||
| 470 | $multipart[] = ['name' => $unique_key, 'contents' => $media]; |
||
| 471 | |||
| 472 | // We're literally overwriting the passed media type data! |
||
| 473 | $media_item->$type = 'attach://' . $unique_key; |
||
| 474 | $media_item->raw_data[$type] = 'attach://' . $unique_key; |
||
| 475 | } |
||
| 476 | } |
||
| 477 | } |
||
| 478 | |||
| 479 | $was_array || $item = reset($item); |
||
| 480 | |||
| 481 | return json_encode($item); |
||
| 482 | } |
||
| 483 | |||
| 484 | /** |
||
| 485 | * Get the current action that's being executed |
||
| 486 | * |
||
| 487 | * @return string |
||
| 488 | */ |
||
| 489 | public static function getCurrentAction(): string |
||
| 490 | { |
||
| 491 | return self::$current_action; |
||
| 492 | } |
||
| 493 | |||
| 494 | /** |
||
| 495 | * Execute HTTP Request |
||
| 496 | * |
||
| 497 | * @param string $action Action to execute |
||
| 498 | * @param array $data Data to attach to the execution |
||
| 499 | * |
||
| 500 | * @return string Result of the HTTP Request |
||
| 501 | * @throws TelegramException |
||
| 502 | */ |
||
| 503 | public static function execute(string $action, array $data = []): string |
||
| 504 | { |
||
| 505 | $request_params = self::setUpRequestParams($data); |
||
| 506 | $request_params['debug'] = TelegramLog::getDebugLogTempStream(); |
||
| 507 | |||
| 508 | try { |
||
| 509 | $response = self::$client->post( |
||
| 510 | '/bot' . self::$telegram->getApiKey() . '/' . $action, |
||
| 511 | $request_params |
||
| 512 | ); |
||
| 513 | $result = (string) $response->getBody(); |
||
| 514 | } catch (RequestException $e) { |
||
| 515 | $response = null; |
||
| 516 | $result = $e->getResponse() ? (string) $e->getResponse()->getBody() : ''; |
||
| 517 | } |
||
| 518 | |||
| 519 | //Logging verbose debug output |
||
| 520 | if (TelegramLog::$always_log_request_and_response || $response === null) { |
||
| 521 | TelegramLog::debug('Request data:' . PHP_EOL . print_r($data, true)); |
||
| 522 | TelegramLog::debug('Response data:' . PHP_EOL . $result); |
||
| 523 | TelegramLog::endDebugLogTempStream('Verbose HTTP Request output:' . PHP_EOL . '%s' . PHP_EOL); |
||
| 524 | } |
||
| 525 | |||
| 526 | return $result; |
||
| 527 | } |
||
| 528 | |||
| 529 | /** |
||
| 530 | * Download file |
||
| 531 | * |
||
| 532 | * @param File $file |
||
| 533 | * |
||
| 534 | * @return bool |
||
| 535 | * @throws TelegramException |
||
| 536 | */ |
||
| 537 | public static function downloadFile(File $file): bool |
||
| 538 | { |
||
| 539 | if (empty($download_path = self::$telegram->getDownloadPath())) { |
||
| 540 | throw new TelegramException('Download path not set!'); |
||
| 541 | } |
||
| 542 | |||
| 543 | $tg_file_path = $file->getFilePath(); |
||
| 544 | $file_path = $download_path . '/' . $tg_file_path; |
||
| 545 | |||
| 546 | $file_dir = dirname($file_path); |
||
| 547 | //For safety reasons, first try to create the directory, then check that it exists. |
||
| 548 | //This is in case some other process has created the folder in the meantime. |
||
| 549 | if (!@mkdir($file_dir, 0755, true) && !is_dir($file_dir)) { |
||
| 550 | throw new TelegramException('Directory ' . $file_dir . ' can\'t be created'); |
||
| 551 | } |
||
| 552 | |||
| 553 | $debug_handle = TelegramLog::getDebugLogTempStream(); |
||
| 554 | |||
| 555 | try { |
||
| 556 | $base_download_uri = str_replace('{API_KEY}', self::$telegram->getApiKey(), self::$api_base_download_uri); |
||
| 557 | self::$client->get( |
||
| 558 | "{$base_download_uri}/{$tg_file_path}", |
||
| 559 | ['debug' => $debug_handle, 'sink' => $file_path] |
||
| 560 | ); |
||
| 561 | |||
| 562 | return filesize($file_path) > 0; |
||
| 563 | } catch (Throwable $e) { |
||
| 564 | return false; |
||
| 565 | } finally { |
||
| 566 | //Logging verbose debug output |
||
| 567 | TelegramLog::endDebugLogTempStream('Verbose HTTP File Download Request output:' . PHP_EOL . '%s' . PHP_EOL); |
||
| 568 | } |
||
| 569 | } |
||
| 570 | |||
| 571 | /** |
||
| 572 | * Encode file |
||
| 573 | * |
||
| 574 | * @param string $file |
||
| 575 | * |
||
| 576 | * @return resource |
||
| 577 | * @throws TelegramException |
||
| 578 | */ |
||
| 579 | public static function encodeFile(string $file) |
||
| 580 | { |
||
| 581 | $fp = fopen($file, 'rb'); |
||
| 582 | if ($fp === false) { |
||
| 583 | throw new TelegramException('Cannot open "' . $file . '" for reading'); |
||
| 584 | } |
||
| 585 | |||
| 586 | return $fp; |
||
| 587 | } |
||
| 588 | |||
| 589 | /** |
||
| 590 | * Send command |
||
| 591 | * |
||
| 592 | * @todo Fake response doesn't need json encoding? |
||
| 593 | * @todo Write debug entry on failure |
||
| 594 | * |
||
| 595 | * @param string $action |
||
| 596 | * @param array $data |
||
| 597 | * |
||
| 598 | * @return ServerResponse |
||
| 599 | * @throws TelegramException |
||
| 600 | */ |
||
| 601 | public static function send(string $action, array $data = []): ServerResponse |
||
| 602 | { |
||
| 603 | self::ensureValidAction($action); |
||
| 604 | self::addDummyParamIfNecessary($action, $data); |
||
| 605 | |||
| 606 | $bot_username = self::$telegram->getBotUsername(); |
||
| 607 | |||
| 608 | if (defined('PHPUNIT_TESTSUITE')) { |
||
| 609 | $fake_response = self::generateGeneralFakeServerResponse($data); |
||
| 610 | |||
| 611 | return new ServerResponse($fake_response, $bot_username); |
||
| 612 | } |
||
| 613 | |||
| 614 | self::ensureNonEmptyData($data); |
||
| 615 | |||
| 616 | self::limitTelegramRequests($action, $data); |
||
| 617 | |||
| 618 | // Remember which action is currently being executed. |
||
| 619 | self::$current_action = $action; |
||
| 620 | |||
| 621 | $raw_response = self::execute($action, $data); |
||
| 622 | $response = json_decode($raw_response, true); |
||
| 623 | |||
| 624 | if (null === $response) { |
||
| 625 | TelegramLog::debug($raw_response); |
||
| 626 | throw new TelegramException('Telegram returned an invalid response!'); |
||
| 627 | } |
||
| 628 | |||
| 629 | $response = new ServerResponse($response, $bot_username); |
||
| 630 | |||
| 631 | if (!$response->isOk() && $response->getErrorCode() === 401 && $response->getDescription() === 'Unauthorized') { |
||
| 632 | throw new InvalidBotTokenException(); |
||
| 633 | } |
||
| 634 | |||
| 635 | // Special case for sent polls, which need to be saved specially. |
||
| 636 | // @todo Take into account if DB gets extracted into separate module. |
||
| 637 | if ($response->isOk() && ($message = $response->getResult()) && ($message instanceof Message) && $poll = $message->getPoll()) { |
||
| 638 | DB::insertPollRequest($poll); |
||
| 639 | } |
||
| 640 | |||
| 641 | // Reset current action after completion. |
||
| 642 | self::$current_action = ''; |
||
| 643 | |||
| 644 | return $response; |
||
| 645 | } |
||
| 646 | |||
| 647 | /** |
||
| 648 | * Add a dummy parameter if the passed action requires it. |
||
| 649 | * |
||
| 650 | * If a method doesn't require parameters, we need to add a dummy one anyway, |
||
| 651 | * because of some cURL version failed POST request without parameters. |
||
| 652 | * |
||
| 653 | * @link https://github.com/php-telegram-bot/core/pull/228 |
||
| 654 | * |
||
| 655 | * @todo Would be nice to find a better solution for this! |
||
| 656 | * |
||
| 657 | * @param string $action |
||
| 658 | * @param array $data |
||
| 659 | */ |
||
| 660 | protected static function addDummyParamIfNecessary(string $action, array &$data): void |
||
| 661 | { |
||
| 662 | if (in_array($action, self::$actions_need_dummy_param, true)) { |
||
| 663 | // Can be anything, using a single letter to minimise request size. |
||
| 664 | $data = ['d']; |
||
| 665 | } |
||
| 666 | } |
||
| 667 | |||
| 668 | /** |
||
| 669 | * Make sure the data isn't empty, else throw an exception |
||
| 670 | * |
||
| 671 | * @param array $data |
||
| 672 | * |
||
| 673 | * @throws TelegramException |
||
| 674 | */ |
||
| 675 | private static function ensureNonEmptyData(array $data): void |
||
| 676 | { |
||
| 677 | if (count($data) === 0) { |
||
| 678 | throw new TelegramException('Data is empty!'); |
||
| 679 | } |
||
| 680 | } |
||
| 681 | |||
| 682 | /** |
||
| 683 | * Make sure the action is valid, else throw an exception |
||
| 684 | * |
||
| 685 | * @param string $action |
||
| 686 | * |
||
| 687 | * @throws TelegramException |
||
| 688 | */ |
||
| 689 | private static function ensureValidAction(string $action): void |
||
| 690 | { |
||
| 691 | if (!in_array($action, self::$actions, true)) { |
||
| 692 | throw new TelegramException('The action "' . $action . '" doesn\'t exist!'); |
||
| 693 | } |
||
| 694 | } |
||
| 695 | |||
| 696 | /** |
||
| 697 | * Use this method to send text messages. On success, the last sent Message is returned |
||
| 698 | * |
||
| 699 | * All message responses are saved in `$extras['responses']`. |
||
| 700 | * Custom encoding can be defined in `$extras['encoding']` (default: `mb_internal_encoding()`) |
||
| 701 | * Custom splitting can be defined in `$extras['split']` (default: 4096) |
||
| 702 | * `$extras['split'] = null;` // force to not split message at all! |
||
| 703 | * `$extras['split'] = 200;` // split message into 200 character chunks |
||
| 704 | * |
||
| 705 | * @link https://core.telegram.org/bots/api#sendmessage |
||
| 706 | * |
||
| 707 | * @todo Splitting formatted text may break the message. |
||
| 708 | * |
||
| 709 | * @param array $data |
||
| 710 | * @param array|null $extras |
||
| 711 | * |
||
| 712 | * @return ServerResponse |
||
| 713 | * @throws TelegramException |
||
| 714 | */ |
||
| 715 | public static function sendMessage(array $data, ?array &$extras = []): ServerResponse |
||
| 716 | { |
||
| 717 | $extras = array_merge([ |
||
| 718 | 'split' => 4096, |
||
| 719 | 'encoding' => mb_internal_encoding(), |
||
| 720 | ], (array) $extras); |
||
| 721 | |||
| 722 | $text = $data['text']; |
||
| 723 | $encoding = $extras['encoding']; |
||
| 724 | $max_length = $extras['split'] ?: mb_strlen($text, $encoding); |
||
| 725 | |||
| 726 | $responses = []; |
||
| 727 | |||
| 728 | do { |
||
| 729 | // Chop off and send the first message. |
||
| 730 | $data['text'] = mb_substr($text, 0, $max_length, $encoding); |
||
| 731 | $responses[] = self::send('sendMessage', $data); |
||
| 732 | |||
| 733 | // Prepare the next message. |
||
| 734 | $text = mb_substr($text, $max_length, null, $encoding); |
||
| 735 | } while ($text !== ''); |
||
| 736 | |||
| 737 | // Add all response objects to referenced variable. |
||
| 738 | $extras['responses'] = $responses; |
||
| 739 | |||
| 740 | return end($responses); |
||
| 741 | } |
||
| 742 | |||
| 743 | /** |
||
| 744 | * Any statically called method should be relayed to the `send` method. |
||
| 745 | * |
||
| 746 | * @param string $action |
||
| 747 | * @param array $data |
||
| 748 | * |
||
| 749 | * @return ServerResponse |
||
| 750 | * @throws TelegramException |
||
| 751 | */ |
||
| 752 | public static function __callStatic(string $action, array $data): ServerResponse |
||
| 753 | { |
||
| 754 | // Only argument should be the data array, ignore any others. |
||
| 755 | return static::send($action, reset($data) ?: []); |
||
| 756 | } |
||
| 757 | |||
| 758 | /** |
||
| 759 | * Return an empty Server Response |
||
| 760 | * |
||
| 761 | * No request is sent to Telegram. |
||
| 762 | * This function is used in commands that don't need to fire a message after execution |
||
| 763 | * |
||
| 764 | * @return ServerResponse |
||
| 765 | */ |
||
| 766 | public static function emptyResponse(): ServerResponse |
||
| 767 | { |
||
| 768 | return new ServerResponse(['ok' => true, 'result' => true]); |
||
| 769 | } |
||
| 770 | |||
| 771 | /** |
||
| 772 | * Send message to all active chats |
||
| 773 | * |
||
| 774 | * @param string $callback_function |
||
| 775 | * @param array $data |
||
| 776 | * @param array $select_chats_params |
||
| 777 | * |
||
| 778 | * @return array |
||
| 779 | * @throws TelegramException |
||
| 780 | */ |
||
| 781 | public static function sendToActiveChats( |
||
| 782 | string $callback_function, |
||
| 783 | array $data, |
||
| 784 | array $select_chats_params |
||
| 785 | ): array { |
||
| 786 | self::ensureValidAction($callback_function); |
||
| 787 | |||
| 788 | $chats = DB::selectChats($select_chats_params); |
||
| 789 | |||
| 790 | $results = []; |
||
| 791 | if (is_array($chats)) { |
||
| 792 | foreach ($chats as $row) { |
||
| 793 | $data['chat_id'] = $row['chat_id']; |
||
| 794 | $results[] = self::send($callback_function, $data); |
||
| 795 | } |
||
| 796 | } |
||
| 797 | |||
| 798 | return $results; |
||
| 799 | } |
||
| 800 | |||
| 801 | /** |
||
| 802 | * Enable request limiter |
||
| 803 | * |
||
| 804 | * @param bool $enable |
||
| 805 | * @param array $options |
||
| 806 | * |
||
| 807 | * @throws TelegramException |
||
| 808 | */ |
||
| 809 | public static function setLimiter(bool $enable = true, array $options = []): void |
||
| 824 | } |
||
| 825 | } |
||
| 826 | |||
| 827 | /** |
||
| 828 | * This functions delays API requests to prevent reaching Telegram API limits |
||
| 829 | * Can be disabled while in execution by 'Request::setLimiter(false)' |
||
| 830 | * |
||
| 831 | * @link https://core.telegram.org/bots/faq#my-bot-is-hitting-limits-how-do-i-avoid-this |
||
| 832 | * |
||
| 833 | * @param string $action |
||
| 834 | * @param array $data |
||
| 835 | * |
||
| 836 | * @throws TelegramException |
||
| 837 | */ |
||
| 838 | private static function limitTelegramRequests(string $action, array $data = []): void |
||
| 839 | { |
||
| 840 | if (self::$limiter_enabled) { |
||
| 841 | $limited_methods = [ |
||
| 908 | } |
||
| 909 | } |
||
| 910 | } |
||
| 912 |