Request::setUpRequestParams()   B
last analyzed

Complexity

Conditions 11
Paths 21

Size

Total Lines 45
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 26
c 2
b 0
f 0
dl 0
loc 45
rs 7.3166
cc 11
nc 21
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace TelegramBot;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Exception\GuzzleException;
7
use TelegramBot\Entities\Response;
8
use TelegramBot\Exception\InvalidBotTokenException;
9
use TelegramBot\Exception\TelegramException;
10
use TelegramBot\Util\Toolkit;
11
12
/**
13
 * Request class
14
 *
15
 *
16
 * Getting updates
17
 * There are two mutually exclusive ways of receiving updates for your bot — the getUpdates method on one hand and Webhooks on the other. Incoming updates are stored on the server until the bot receives them either way, but they will not be kept longer than 24 hours.
18
 *
19
 * @method static Response getUpdates(array $data)      Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.
20
 * @method static Response setWebhook(array $data)      Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns true.
21
 * @method static Response deleteWebhook(array $data)   Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success.
22
 * @method static Response getWebhookInfo()             Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.
23
 *
24
 *
25
 * Available methods
26
 * All methods in the Bot API are case-insensitive.
27
 *
28
 * @method static Response getMe()                                        A simple method for testing your bots auth token. Requires no parameters. Returns basic information about the bot in form of a User object.
29
 * @method static Response logOut()                                       Use this method to log out from the cloud Bot API server before launching the bot locally. Requires no parameters. Returns True on success.
30
 * @method static Response close()                                        Use this method to close the bot instance before moving it from one local server to another. Requires no parameters. Returns True on success.
31
 * @method static Response sendMessage(array $data)                       Use this method to send any kind of message. On success, the sent Message is returned.
32
 * @method static Response forwardMessage(array $data)                    Use this method to forward messages of any kind. On success, the sent Message is returned.
33
 * @method static Response copyMessage(array $data)                       Use this method to copy messages of any kind. The method is analogous to the method forwardMessages, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success.
34
 * @method static Response sendPhoto(array $data)                         Use this method to send photos. On success, the sent Message is returned.
35
 * @method static Response sendAudio(array $data)                         Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .mp3 format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
36
 * @method static Response sendDocument(array $data)                      Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
37
 * @method static Response sendVideo(array $data)                         Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
38
 * @method static Response sendAnimation(array $data)                     Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.
39
 * @method static Response sendVoice(array $data)                         Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
40
 * @method static Response sendVideoNote(array $data)                     Use this method to send video messages. On success, the sent Message is returned.
41
 * @method static Response sendMediaGroup(array $data)                    Use this method to send a group of photos or videos as an album. On success, an array of the sent Messages is returned.
42
 * @method static Response sendLocation(array $data)                      Use this method to send point on the map. On success, the sent Message is returned.
43
 * @method static Response editMessageLiveLocation(array $data)           Use this method to edit live location messages sent by the bot or via the bot (for inline bots). A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned.
44
 * @method static Response stopMessageLiveLocation(array $data)           Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires. On success, if the message was sent by the bot, the sent Message is returned, otherwise True is returned.
45
 * @method static Response sendVenue(array $data)                         Use this method to send information about a venue. On success, the sent Message is returned.
46
 * @method static Response sendContact(array $data)                       Use this method to send phone contacts. On success, the sent Message is returned.
47
 * @method static Response sendPoll(array $data)                          Use this method to send a native poll. A native poll can't be sent to a private chat. On success, the sent Message is returned.
48
 * @method static Response sendDice(array $data)                          Use this method to send a dice, which will have a random value from 1 to 6. On success, the sent Message is returned.
49
 * @method static Response sendChatAction(array $data)                    Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success.
50
 * @method static Response getUserProfilePhotos(array $data)              Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
51
 * @method static Response getFile(array $data)                           Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>, where <file_path> is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again.
52
 * @method static Response banChatMember(array $data)                     Use this method to kick a user from a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the group on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
53
 * @method static Response unbanChatMember(array $data)                   Use this method to unban a previously kicked user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. Returns True on success.
54
 * @method static Response restrictChatMember(array $data)                Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all permissions to lift restrictions from a user. Returns True on success.
55
 * @method static Response promoteChatMember(array $data)                 Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user. Returns True on success.
56
 * @method static Response setChatAdministratorCustomTitle(array $data)   Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success.
57
 * @method static Response banChatSenderChat(array $data)                 Use this method to ban a channel chat in a supergroup or a channel. Until the chat is unbanned, the owner of the banned chat won't be able to send messages on behalf of any of their channels. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns True on success.
58
 * @method static Response unbanChatSenderChat(array $data)               Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns True on success.
59
 * @method static Response setChatPermissions(array $data)                Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the can_restrict_members admin rights. Returns True on success.
60
 * @method static Response exportChatInviteLink(array $data)              Use this method to generate a new invite link for a chat. Any previously generated link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns the new invite link as String on success.
61
 * @method static Response createChatInviteLink(array $data)              Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as ChatInviteLink object.
62
 * @method static Response editChatInviteLink(array $data)                Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns the edited invite link as a ChatInviteLink object.
63
 * @method static Response revokeChatInviteLink(array $data)              Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns the revoked invite link as ChatInviteLink object.
64
 * @method static Response approveChatJoinRequest(array $data)            Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.
65
 * @method static Response declineChatJoinRequest(array $data)            Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.
66
 * @method static Response setChatPhoto(array $data)                      Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
67
 * @method static Response deleteChatPhoto(array $data)                   Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
68
 * @method static Response setChatTitle(array $data)                      Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
69
 * @method static Response setChatDescription(array $data)                Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
70
 * @method static Response pinChatMessage(array $data)                    Use this method to pin a message in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right in the channel. Returns True on success.
71
 * @method static Response unpinChatMessage(array $data)                  Use this method to unpin a message in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right in the channel. Returns True on success.
72
 * @method static Response unpinAllChatMessages(array $data)              Use this method to clear the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' admin right in a supergroup or 'can_edit_messages' admin right in a channel. Returns True on success.
73
 * @method static Response leaveChat(array $data)                         Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
74
 * @method static Response getChat(array $data)                           Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success.
75
 * @method static Response getChatAdministrators(array $data)             Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.
76
 * @method static Response getChatMemberCount(array $data)                Use this method to get the number of members in a chat. Returns Int on success.
77
 * @method static Response getChatMember(array $data)                     Use this method to get information about a member of a chat. Returns a ChatMember object on success.
78
 * @method static Response setChatStickerSet(array $data)                 Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.
79
 * @method static Response deleteChatStickerSet(array $data)              Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.
80
 * @method static Response answerCallbackQuery(array $data)               Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned.
81
 * @method static Response setMyCommands(array $data)                     Use this method to change the list of the bot's commands. Returns True on success.
82
 * @method static Response deleteMyCommands(array $data)                  Use this method to delete the list of the bot's commands for the given scope and user language. After deletion, higher level commands will be shown to affected users. Returns True on success.
83
 * @method static Response getMyCommands()                                Use this method to get the current list of the bot's commands. Requires no parameters. Returns Array of BotCommand on success.
84
 * @method static Response setChatMenuButton()                            Use this method to change the bot's menu button in a private chat, or the default menu button. Returns True on success.
85
 * @method static Response getChatMenuButton()                            Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. Returns MenuButton on success.
86
 * @method static Response setMyDefaultAdministratorRights()              Use this method to change the default administrator rights requested by the bot when it's added as an administrator to groups or channels. These rights will be suggested to users, but they are are free to modify the list before adding the bot. Returns True on success.
87
 * @method static Response getMyDefaultAdministratorRights()              Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success.
88
 *
89
 *
90
 * Updating messages
91
 * The following methods allow you to change an existing message in the message history instead of sending a new one with a result of an action. This is most useful for messages with inline keyboards using callback queries, but can also help reduce clutter in conversations with regular chat bots.
92
 *
93
 * @method static Response editMessageText(array $data)          Use this method to edit text and game messages sent by the bot or via the bot (for inline bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
94
 * @method static Response editMessageCaption(array $data)       Use this method to edit captions of messages sent by the bot or via the bot (for inline bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
95
 * @method static Response editMessageMedia(array $data)         Use this method to edit audio, document, photo, or video messages. On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned.
96
 * @method static Response editMessageReplyMarkup(array $data)   Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
97
 * @method static Response stopPoll(array $data)                 Use this method to stop a poll which was sent by the bot. On success, the stopped Poll with the final results is returned.
98
 * @method static Response deleteMessage(array $data)            Use this method to delete a message, including service messages, with certain limitations. Returns True on success.
99
 *
100
 *
101
 * Stickers
102
 * The following methods and objects allow your bot to handle stickers and sticker sets.
103
 *
104
 * @method static Response sendSticker(array $data)               Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned.
105
 * @method static Response getStickerSet(array $data)             Use this method to get a sticker set. On success, a StickerSet object is returned.
106
 * @method static Response uploadStickerFile(array $data)         Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success.
107
 * @method static Response createNewStickerSet(array $data)       Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. Returns True on success.
108
 * @method static Response addStickerToSet(array $data)           Use this method to add a new sticker to a set created by the bot. Returns True on success.
109
 * @method static Response setStickerPositionInSet(array $data)   Use this method to move a sticker in a set created by the bot to a specific position. Returns True on success.
110
 * @method static Response deleteStickerFromSet(array $data)      Use this method to delete a sticker from a set created by the bot. Returns True on success.
111
 * @method static Response setStickerSetThumb(array $data)        Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated sticker sets only. Returns True on success.
112
 *
113
 *
114
 * Inline mode
115
 * The following methods and objects allow your bot to work in inline mode.
116
 *
117
 * @method static Response answerInlineQuery(array $data)   Use this method to send answers to an inline query. On success, True is returned.
118
 * @method static Response answerWebAppQuery(array $data)   Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a SentWebAppMessage object is returned.
119
 * @method static Response SentWebAppMessage(array $data)   Contains information about an inline message sent by a Web App on behalf of a user.
120
 *
121
 *
122
 * Payments
123
 * Your bot can accept payments from Telegram users. Please see the introduction to payments for more details on the process and how to set up payments for your bot.
124
 *
125
 * @method static Response sendInvoice(array $data)              Use this method to send invoices. On success, the sent Message is returned.
126
 * @method static Response answerShippingQuery(array $data)      If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned.
127
 * @method static Response answerPreCheckoutQuery(array $data)   Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned.
128
 *
129
 *
130
 * Telegram Passport
131
 * Telegram Passport is a unified authorization method for services that require personal identification. Users can upload their documents once, then instantly share their data with services that require real-world ID (finance, ICOs, etc.).
132
 *
133
 * @method static Response setPassportDataErrors(array $data)   Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success. Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues.
134
 *
135
 *
136
 * Games
137
 * our bot can offer users HTML5 games to play solo or to compete against each other in groups and one-on-one chats. Create games via @BotFather using the /newgame command. Please note that this kind of power requires responsibility: you will need to accept the terms for each game that your bots will be offering.
138
 *
139
 * @method static Response sendGame(array $data)            our bot can offer users HTML5 games to play solo or to compete against each other in groups and one-on-one chats. Create games via @BotFather using the /newgame command. Please note that this kind of power requires responsibility: you will need to accept the terms for each game that your bots will be offering.
140
 * @method static Response setGameScore(array $data)        Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat and force is False.
141
 * @method static Response getGameHighScores(array $data)   Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects.
142
 */
143
class Request {
144
145
    /**
146
     * Available fields for InputFile helper
147
     *
148
     * This is basically the list of all fields that allow InputFile objects
149
     * for which input can be simplified by providing local path directly  as string.
150
     *
151
     * @var array
152
     */
153
    private static array $input_file_fields = [
154
        'setWebhook' => ['certificate'],
155
        'sendPhoto' => ['photo'],
156
        'sendAudio' => ['audio', 'thumb'],
157
        'sendDocument' => ['document', 'thumb'],
158
        'sendVideo' => ['video', 'thumb'],
159
        'sendAnimation' => ['animation', 'thumb'],
160
        'sendVoice' => ['voice', 'thumb'],
161
        'sendVideoNote' => ['video_note', 'thumb'],
162
        'setChatPhoto' => ['photo'],
163
        'sendSticker' => ['sticker'],
164
        'uploadStickerFile' => ['png_sticker'],
165
        'createNewStickerSet' => ['png_sticker', 'tgs_sticker', 'webm_sticker'],
166
        'addStickerToSet' => ['png_sticker', 'tgs_sticker', 'webm_sticker'],
167
        'setStickerSetThumb' => ['thumb'],
168
    ];
169
170
    /**
171
     * URI of the Telegram API
172
     *
173
     * @var string
174
     */
175
    private static string $api_base_uri = 'https://api.telegram.org';
176
177
    /**
178
     * URI of the Telegram API for downloading files (relative to $api_base_url or absolute)
179
     *
180
     * @var string
181
     */
182
    private static string $api_base_download_uri = '/file/bot{API_KEY}';
0 ignored issues
show
introduced by
The private property $api_base_download_uri is not used, and could be removed.
Loading history...
183
184
    /**
185
     * The current action that is being executed
186
     *
187
     * @var string
188
     */
189
    private static string $current_action = '';
190
191
    /**
192
     * The temporary token used for the current action
193
     *
194
     * @var string
195
     */
196
    private static string $current_token = '';
197
198
    /**
199
     * Use this method to get stats of given user in a supergroup or channel.
200
     *
201
     * @param int $user_id User identifier
202
     * @param int $chat_id Identifier of the chat to get stats for
203
     *
204
     * @return string {left, member, administrator, creator}
205
     */
206
    public static function getChatMemberStatus(int $user_id, int $chat_id): string {
207
        $response = self::getChatMember([
208
            'user_id' => $user_id,
209
            'chat_id' => $chat_id,
210
        ]);
211
212
        return $response->getResult()->status ?? "left";
213
    }
214
215
    /**
216
     * Any statically called method should be relayed to the `send` method.
217
     *
218
     * @param string $name
219
     * @param array $arguments
220
     *
221
     * @return Response
222
     * @throws TelegramException
223
     */
224
    public static function __callStatic(string $name, array $arguments) {
225
        if (isset($arguments[1])) {
226
            self::$current_token = $arguments[1];
227
        }
228
229
        return static::send($name, reset($arguments) ?: []);
230
    }
231
232
    /**
233
     * Send command
234
     *
235
     * @param string $action
236
     * @param array $data
237
     *
238
     * @return Response
239
     * @throws TelegramException
240
     */
241
    public static function send(string $action, array $data = []): Response {
242
        self::$current_action = $action;
243
244
        $raw_response = self::execute($action, $data);
245
246
        if (!Toolkit::isJson($raw_response)) {
247
            TelegramLog::error($raw_response);
248
            throw new TelegramException('Invalid response from API');
249
        }
250
251
        $response = new Response(json_decode($raw_response, true));
252
253
        if (!$response->isOk() && $response->getErrorCode() === 401 && $response->getDescription() === 'Unauthorized') {
254
            throw new InvalidBotTokenException();
255
        }
256
257
        self::$current_action = '';
258
        static::$current_token = '';
0 ignored issues
show
Bug introduced by
Since $current_token is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $current_token to at least protected.
Loading history...
259
260
        return $response;
261
    }
262
263
    /**
264
     * Execute HTTP Request
265
     *
266
     * @param string $action Action to execute
267
     * @param array $data Data to attach to the execution
268
     *
269
     * @return string Result of the HTTP Request
270
     * @throws GuzzleException
271
     */
272
    private static function execute(string $action, array $data): string {
273
        $request = self::create($action, $data);
274
275
        $response = self::getClient()->request($request['method'], $request['url'], $request['options']);
276
277
        return $response->getBody();
278
    }
279
280
    /**
281
     * Create a Http Request
282
     *
283
     * @param string $action Action to execute
284
     * @param array $data Data to attach to the execution
285
     *
286
     * @return array An array of the setUpRequestParams and the url
287
     */
288
    public static function create(string $action, array $data): array {
289
        if (isset($data['bot_token'])) {
290
            self::$current_token = $data['bot_token'];
291
        }
292
293
        $opts = self::setUpRequestParams($data);
294
295
        return [
296
            'url' => self::getApiPath() . $action,
297
            'method' => isset($opts['multipart']) && count($opts['multipart']) > 0 ? 'POST' : 'GET',
298
            'options' => $opts,
299
        ];
300
    }
301
302
    /**
303
     * Get the Telegram API path
304
     *
305
     * @return string
306
     */
307
    public static function getApiPath(): string {
308
        if (static::$current_token !== '') {
0 ignored issues
show
Bug introduced by
Since $current_token is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $current_token to at least protected.
Loading history...
309
            return self::$api_base_uri . '/bot' . static::$current_token . '/';
310
        }
311
312
        return self::$api_base_uri . '/bot' . Telegram::getApiToken() . '/';
0 ignored issues
show
Bug introduced by
Are you sure TelegramBot\Telegram::getApiToken() of type false|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

312
        return self::$api_base_uri . '/bot' . /** @scrutinizer ignore-type */ Telegram::getApiToken() . '/';
Loading history...
313
    }
314
315
    /**
316
     * Properly set up the request params
317
     *
318
     * If any item of the array is a resource, reformat it to a multipart request.
319
     * Else, just return the passed data as form params.
320
     *
321
     * @param array $data
322
     * @return array
323
     */
324
    private static function setUpRequestParams(array $data): array {
325
        $multipart = [];
326
        $has_resource = false;
327
328
        $options = [
329
            'headers' => [
330
                'Accept' => 'application/json',
331
                'User-Agent' => 'TelegramBot-PHP/' . Telegram::$VERSION
332
            ]
333
        ];
334
335
        foreach ($data as $key => &$item) {
336
            if (array_key_exists(self::$current_action, self::$input_file_fields) && in_array($key, self::$input_file_fields[self::$current_action], true)) {
337
                if (is_string($item) && file_exists($item)) {
338
                    $multipart[] = [
339
                        'name' => $key,
340
                        'contents' => fopen($item, 'r')
341
                    ];
342
                    $has_resource = true;
343
344
                    continue;
345
                } elseif (str_contains($item, '/') && !filter_var($item, FILTER_VALIDATE_URL)) {
346
                    throw new TelegramException(
347
                        'Invalid file path or URL: ' . $item . ' for ' . self::$current_action . ' action'
348
                    );
349
                }
350
            }
351
352
            if ($item instanceof Entity) {
353
                $item = $item->getRawData();
354
            }
355
356
            if (is_array($item)) {
357
                $item = json_encode($item);
358
            }
359
360
            $options['query'][$key] = $item;
361
        }
362
        unset($item);
363
364
        if ($has_resource) {
365
            $options['multipart'] = $multipart;
366
        }
367
368
        return $options;
369
    }
370
371
    /**
372
     * Initialize a http client
373
     *
374
     * @return Client
375
     */
376
    private static function getClient(): Client {
377
        return new Client();
378
    }
379
380
}
381