Passed
Push — master ( f78b46...593eca )
by Shahrad
02:40
created
src/lib/Request.php 1 patch
Indentation   +222 added lines, -222 removed lines patch added patch discarded remove patch
@@ -143,227 +143,227 @@
 block discarded – undo
143 143
 class Request
144 144
 {
145 145
 
146
-	/**
147
-	 * Available fields for InputFile helper
148
-	 *
149
-	 * This is basically the list of all fields that allow InputFile objects
150
-	 * for which input can be simplified by providing local path directly  as string.
151
-	 *
152
-	 * @var array
153
-	 */
154
-	private static array $input_file_fields = [
155
-		'setWebhook' => ['certificate'],
156
-		'sendPhoto' => ['photo'],
157
-		'sendAudio' => ['audio', 'thumb'],
158
-		'sendDocument' => ['document', 'thumb'],
159
-		'sendVideo' => ['video', 'thumb'],
160
-		'sendAnimation' => ['animation', 'thumb'],
161
-		'sendVoice' => ['voice', 'thumb'],
162
-		'sendVideoNote' => ['video_note', 'thumb'],
163
-		'setChatPhoto' => ['photo'],
164
-		'sendSticker' => ['sticker'],
165
-		'uploadStickerFile' => ['png_sticker'],
166
-		'createNewStickerSet' => ['png_sticker', 'tgs_sticker', 'webm_sticker'],
167
-		'addStickerToSet' => ['png_sticker', 'tgs_sticker', 'webm_sticker'],
168
-		'setStickerSetThumb' => ['thumb'],
169
-	];
170
-
171
-	/**
172
-	 * URI of the Telegram API
173
-	 *
174
-	 * @var string
175
-	 */
176
-	private static string $api_base_uri = 'https://api.telegram.org';
177
-
178
-	/**
179
-	 * URI of the Telegram API for downloading files (relative to $api_base_url or absolute)
180
-	 *
181
-	 * @var string
182
-	 */
183
-	private static string $api_base_download_uri = '/file/bot{API_KEY}';
184
-
185
-	/**
186
-	 * The current action that is being executed
187
-	 *
188
-	 * @var string
189
-	 */
190
-	private static string $current_action = '';
191
-
192
-	/**
193
-	 * Get the Telegram API path
194
-	 *
195
-	 * @return string
196
-	 */
197
-	public static function getApiPath(): string
198
-	{
199
-		return self::$api_base_uri . '/bot' . Telegram::getApiKey() . '/';
200
-	}
201
-
202
-	/**
203
-	 * Initialize a http client
204
-	 *
205
-	 * @return Client
206
-	 */
207
-	private static function getClient(): Client
208
-	{
209
-		return new Client();
210
-	}
211
-
212
-	/**
213
-	 * Use this method to get stats of given user in a supergroup or channel.
214
-	 *
215
-	 * @param int $user_id User identifier
216
-	 * @param int $chat_id Identifier of the chat to get stats for
217
-	 *
218
-	 * @return string [left, member, administrator, creator]
219
-	 */
220
-	public static function getChatMemberStatus(int $user_id, int $chat_id): string
221
-	{
222
-		$response = self::getChatMember([
223
-			'user_id' => $user_id,
224
-			'chat_id' => $chat_id,
225
-		]);
226
-
227
-		return $response->getResult()->status ?? "left";
228
-	}
229
-
230
-	/**
231
-	 * Properly set up the request params
232
-	 *
233
-	 * If any item of the array is a resource, reformat it to a multipart request.
234
-	 * Else, just return the passed data as form params.
235
-	 *
236
-	 * @param array $data
237
-	 * @return array
238
-	 */
239
-	private static function setUpRequestParams(array $data): array
240
-	{
241
-		$multipart = [];
242
-		$has_resource = false;
243
-
244
-		$options = [
245
-			'header' => [
246
-				'Content-Type' => 'application/json',
247
-				'Accept' => 'application/json',
248
-				'User-Agent' => 'TelegramBot-PHP/' . Telegram::$VERSION
249
-			]
250
-		];
251
-
252
-		foreach ($data as $key => &$item) {
253
-			if (array_key_exists(self::$current_action, self::$input_file_fields) && in_array($key, self::$input_file_fields[self::$current_action], true)) {
254
-
255
-				if (is_string($item) && file_exists($item)) {
256
-					$has_resource = true;
257
-
258
-				} elseif (filter_var($item, FILTER_VALIDATE_URL)) {
259
-					$has_resource = false;
260
-					continue;
261
-
262
-				} else {
263
-					throw new TelegramException(
264
-						'Invalid file path or URL: ' . $item . ' for ' . self::$current_action . ' action'
265
-					);
266
-				}
267
-
268
-				$multipart[$key] = $item;
269
-				continue;
270
-			}
271
-
272
-			if ($item instanceof Entity) {
273
-				$item = $item->getRawData();
274
-			}
275
-
276
-			if (is_array($item)) {
277
-				$item = json_encode($item);
278
-			}
279
-
280
-			$options['query'][$key] = $item;
281
-		}
282
-		unset($item);
283
-
284
-		if ($has_resource) {
285
-			$options['multipart'] = FormData::create($multipart);
286
-		}
287
-
288
-		return $options;
289
-	}
290
-
291
-	/**
292
-	 * Create a Http Request
293
-	 *
294
-	 * @param string $action Action to execute
295
-	 * @param array $data Data to attach to the execution
296
-	 *
297
-	 * @return array An array of the setUpRequestParams and the url
298
-	 */
299
-	public static function create(string $action, array $data): array
300
-	{
301
-		return [
302
-			'url' => self::getApiPath() . $action,
303
-			'options' => self::setUpRequestParams($data)
304
-		];
305
-	}
306
-
307
-	/**
308
-	 * Execute HTTP Request
309
-	 *
310
-	 * @param string $action Action to execute
311
-	 * @param array $data Data to attach to the execution
312
-	 *
313
-	 * @return string Result of the HTTP Request
314
-	 */
315
-	private static function execute(string $action, array $data): string
316
-	{
317
-		$request = self::create($action, $data);
318
-
319
-		$response = self::getClient()->get($request['url'], $request['options']);
320
-
321
-		return $response->getBody();
322
-	}
323
-
324
-	/**
325
-	 * Send command
326
-	 *
327
-	 * @param string $action
328
-	 * @param array $data
329
-	 *
330
-	 * @return Response
331
-	 * @throws TelegramException
332
-	 */
333
-	public static function send(string $action, array $data = []): Response
334
-	{
335
-		self::$current_action = $action;
336
-
337
-		$raw_response = self::execute($action, $data);
338
-
339
-		if (!Common::isJson($raw_response)) {
340
-			TelegramLog::debug($raw_response);
341
-			throw new TelegramException('Invalid response from API');
342
-		}
343
-
344
-		$response = new Response(json_decode($raw_response, true));
345
-
346
-		if (!$response->isOk() && $response->getErrorCode() === 401 && $response->getDescription() === 'Unauthorized') {
347
-			throw new InvalidBotTokenException();
348
-		}
349
-
350
-		self::$current_action = '';
351
-
352
-		return $response;
353
-	}
354
-
355
-	/**
356
-	 * Any statically called method should be relayed to the `send` method.
357
-	 *
358
-	 * @param string $action
359
-	 * @param array $data
360
-	 *
361
-	 * @return Response
362
-	 * @throws TelegramException
363
-	 */
364
-	public static function __callStatic(string $action, array $data): Response
365
-	{
366
-		return static::send($action, reset($data) ?: []);
367
-	}
146
+    /**
147
+     * Available fields for InputFile helper
148
+     *
149
+     * This is basically the list of all fields that allow InputFile objects
150
+     * for which input can be simplified by providing local path directly  as string.
151
+     *
152
+     * @var array
153
+     */
154
+    private static array $input_file_fields = [
155
+        'setWebhook' => ['certificate'],
156
+        'sendPhoto' => ['photo'],
157
+        'sendAudio' => ['audio', 'thumb'],
158
+        'sendDocument' => ['document', 'thumb'],
159
+        'sendVideo' => ['video', 'thumb'],
160
+        'sendAnimation' => ['animation', 'thumb'],
161
+        'sendVoice' => ['voice', 'thumb'],
162
+        'sendVideoNote' => ['video_note', 'thumb'],
163
+        'setChatPhoto' => ['photo'],
164
+        'sendSticker' => ['sticker'],
165
+        'uploadStickerFile' => ['png_sticker'],
166
+        'createNewStickerSet' => ['png_sticker', 'tgs_sticker', 'webm_sticker'],
167
+        'addStickerToSet' => ['png_sticker', 'tgs_sticker', 'webm_sticker'],
168
+        'setStickerSetThumb' => ['thumb'],
169
+    ];
170
+
171
+    /**
172
+     * URI of the Telegram API
173
+     *
174
+     * @var string
175
+     */
176
+    private static string $api_base_uri = 'https://api.telegram.org';
177
+
178
+    /**
179
+     * URI of the Telegram API for downloading files (relative to $api_base_url or absolute)
180
+     *
181
+     * @var string
182
+     */
183
+    private static string $api_base_download_uri = '/file/bot{API_KEY}';
184
+
185
+    /**
186
+     * The current action that is being executed
187
+     *
188
+     * @var string
189
+     */
190
+    private static string $current_action = '';
191
+
192
+    /**
193
+     * Get the Telegram API path
194
+     *
195
+     * @return string
196
+     */
197
+    public static function getApiPath(): string
198
+    {
199
+        return self::$api_base_uri . '/bot' . Telegram::getApiKey() . '/';
200
+    }
201
+
202
+    /**
203
+     * Initialize a http client
204
+     *
205
+     * @return Client
206
+     */
207
+    private static function getClient(): Client
208
+    {
209
+        return new Client();
210
+    }
211
+
212
+    /**
213
+     * Use this method to get stats of given user in a supergroup or channel.
214
+     *
215
+     * @param int $user_id User identifier
216
+     * @param int $chat_id Identifier of the chat to get stats for
217
+     *
218
+     * @return string [left, member, administrator, creator]
219
+     */
220
+    public static function getChatMemberStatus(int $user_id, int $chat_id): string
221
+    {
222
+        $response = self::getChatMember([
223
+            'user_id' => $user_id,
224
+            'chat_id' => $chat_id,
225
+        ]);
226
+
227
+        return $response->getResult()->status ?? "left";
228
+    }
229
+
230
+    /**
231
+     * Properly set up the request params
232
+     *
233
+     * If any item of the array is a resource, reformat it to a multipart request.
234
+     * Else, just return the passed data as form params.
235
+     *
236
+     * @param array $data
237
+     * @return array
238
+     */
239
+    private static function setUpRequestParams(array $data): array
240
+    {
241
+        $multipart = [];
242
+        $has_resource = false;
243
+
244
+        $options = [
245
+            'header' => [
246
+                'Content-Type' => 'application/json',
247
+                'Accept' => 'application/json',
248
+                'User-Agent' => 'TelegramBot-PHP/' . Telegram::$VERSION
249
+            ]
250
+        ];
251
+
252
+        foreach ($data as $key => &$item) {
253
+            if (array_key_exists(self::$current_action, self::$input_file_fields) && in_array($key, self::$input_file_fields[self::$current_action], true)) {
254
+
255
+                if (is_string($item) && file_exists($item)) {
256
+                    $has_resource = true;
257
+
258
+                } elseif (filter_var($item, FILTER_VALIDATE_URL)) {
259
+                    $has_resource = false;
260
+                    continue;
261
+
262
+                } else {
263
+                    throw new TelegramException(
264
+                        'Invalid file path or URL: ' . $item . ' for ' . self::$current_action . ' action'
265
+                    );
266
+                }
267
+
268
+                $multipart[$key] = $item;
269
+                continue;
270
+            }
271
+
272
+            if ($item instanceof Entity) {
273
+                $item = $item->getRawData();
274
+            }
275
+
276
+            if (is_array($item)) {
277
+                $item = json_encode($item);
278
+            }
279
+
280
+            $options['query'][$key] = $item;
281
+        }
282
+        unset($item);
283
+
284
+        if ($has_resource) {
285
+            $options['multipart'] = FormData::create($multipart);
286
+        }
287
+
288
+        return $options;
289
+    }
290
+
291
+    /**
292
+     * Create a Http Request
293
+     *
294
+     * @param string $action Action to execute
295
+     * @param array $data Data to attach to the execution
296
+     *
297
+     * @return array An array of the setUpRequestParams and the url
298
+     */
299
+    public static function create(string $action, array $data): array
300
+    {
301
+        return [
302
+            'url' => self::getApiPath() . $action,
303
+            'options' => self::setUpRequestParams($data)
304
+        ];
305
+    }
306
+
307
+    /**
308
+     * Execute HTTP Request
309
+     *
310
+     * @param string $action Action to execute
311
+     * @param array $data Data to attach to the execution
312
+     *
313
+     * @return string Result of the HTTP Request
314
+     */
315
+    private static function execute(string $action, array $data): string
316
+    {
317
+        $request = self::create($action, $data);
318
+
319
+        $response = self::getClient()->get($request['url'], $request['options']);
320
+
321
+        return $response->getBody();
322
+    }
323
+
324
+    /**
325
+     * Send command
326
+     *
327
+     * @param string $action
328
+     * @param array $data
329
+     *
330
+     * @return Response
331
+     * @throws TelegramException
332
+     */
333
+    public static function send(string $action, array $data = []): Response
334
+    {
335
+        self::$current_action = $action;
336
+
337
+        $raw_response = self::execute($action, $data);
338
+
339
+        if (!Common::isJson($raw_response)) {
340
+            TelegramLog::debug($raw_response);
341
+            throw new TelegramException('Invalid response from API');
342
+        }
343
+
344
+        $response = new Response(json_decode($raw_response, true));
345
+
346
+        if (!$response->isOk() && $response->getErrorCode() === 401 && $response->getDescription() === 'Unauthorized') {
347
+            throw new InvalidBotTokenException();
348
+        }
349
+
350
+        self::$current_action = '';
351
+
352
+        return $response;
353
+    }
354
+
355
+    /**
356
+     * Any statically called method should be relayed to the `send` method.
357
+     *
358
+     * @param string $action
359
+     * @param array $data
360
+     *
361
+     * @return Response
362
+     * @throws TelegramException
363
+     */
364
+    public static function __callStatic(string $action, array $data): Response
365
+    {
366
+        return static::send($action, reset($data) ?: []);
367
+    }
368 368
 
369 369
 }
Please login to merge, or discard this patch.