Passed
Push — master ( 9c7b82...f78b46 )
by Shahrad
02:20
created
src/lib/Request.php 1 patch
Indentation   +222 added lines, -222 removed lines patch added patch discarded remove patch
@@ -145,227 +145,227 @@
 block discarded – undo
145 145
 class Request
146 146
 {
147 147
 
148
-	/**
149
-	 * Available fields for InputFile helper
150
-	 *
151
-	 * This is basically the list of all fields that allow InputFile objects
152
-	 * for which input can be simplified by providing local path directly  as string.
153
-	 *
154
-	 * @var array
155
-	 */
156
-	private static array $input_file_fields = [
157
-		'setWebhook' => ['certificate'],
158
-		'sendPhoto' => ['photo'],
159
-		'sendAudio' => ['audio', 'thumb'],
160
-		'sendDocument' => ['document', 'thumb'],
161
-		'sendVideo' => ['video', 'thumb'],
162
-		'sendAnimation' => ['animation', 'thumb'],
163
-		'sendVoice' => ['voice', 'thumb'],
164
-		'sendVideoNote' => ['video_note', 'thumb'],
165
-		'setChatPhoto' => ['photo'],
166
-		'sendSticker' => ['sticker'],
167
-		'uploadStickerFile' => ['png_sticker'],
168
-		'createNewStickerSet' => ['png_sticker', 'tgs_sticker', 'webm_sticker'],
169
-		'addStickerToSet' => ['png_sticker', 'tgs_sticker', 'webm_sticker'],
170
-		'setStickerSetThumb' => ['thumb'],
171
-	];
172
-
173
-	/**
174
-	 * URI of the Telegram API
175
-	 *
176
-	 * @var string
177
-	 */
178
-	private static string $api_base_uri = 'https://api.telegram.org';
179
-
180
-	/**
181
-	 * URI of the Telegram API for downloading files (relative to $api_base_url or absolute)
182
-	 *
183
-	 * @var string
184
-	 */
185
-	private static string $api_base_download_uri = '/file/bot{API_KEY}';
186
-
187
-	/**
188
-	 * The current action that is being executed
189
-	 *
190
-	 * @var string
191
-	 */
192
-	private static string $current_action = '';
193
-
194
-	/**
195
-	 * Get the Telegram API path
196
-	 *
197
-	 * @return string
198
-	 */
199
-	public static function getApiPath(): string
200
-	{
201
-		return self::$api_base_uri . '/bot' . Telegram::getApiKey() . '/';
202
-	}
203
-
204
-	/**
205
-	 * Initialize a http client
206
-	 *
207
-	 * @return Client
208
-	 */
209
-	private static function getClient(): Client
210
-	{
211
-		return new Client();
212
-	}
213
-
214
-	/**
215
-	 * Use this method to get stats of given user in a supergroup or channel.
216
-	 *
217
-	 * @param int $user_id User identifier
218
-	 * @param int $chat_id Identifier of the chat to get stats for
219
-	 *
220
-	 * @return string [left, member, administrator, creator]
221
-	 */
222
-	public static function getChatMemberStatus(int $user_id, int $chat_id): string
223
-	{
224
-		$response = self::getChatMember([
225
-			'user_id' => $user_id,
226
-			'chat_id' => $chat_id,
227
-		]);
228
-
229
-		return $response->getResult()->status ?? "left";
230
-	}
231
-
232
-	/**
233
-	 * Properly set up the request params
234
-	 *
235
-	 * If any item of the array is a resource, reformat it to a multipart request.
236
-	 * Else, just return the passed data as form params.
237
-	 *
238
-	 * @param array $data
239
-	 * @return array
240
-	 */
241
-	private static function setUpRequestParams(array $data): array
242
-	{
243
-		$multipart = [];
244
-		$has_resource = false;
245
-
246
-		$options = [
247
-			'header' => [
248
-				'Content-Type' => 'application/json',
249
-				'Accept' => 'application/json',
250
-				'User-Agent' => 'TelegramBot-PHP/' . Telegram::$VERSION
251
-			]
252
-		];
253
-
254
-		foreach ($data as $key => &$item) {
255
-			if (array_key_exists(self::$current_action, self::$input_file_fields) && in_array($key, self::$input_file_fields[self::$current_action], true)) {
256
-
257
-				if (is_string($item) && file_exists($item)) {
258
-					$has_resource = true;
259
-
260
-				} elseif (filter_var($item, FILTER_VALIDATE_URL)) {
261
-					$has_resource = false;
262
-					continue;
263
-
264
-				} else {
265
-					throw new TelegramException(
266
-						'Invalid file path or URL: ' . $item . ' for ' . self::$current_action . ' action'
267
-					);
268
-				}
269
-
270
-				$multipart[$key] = $item;
271
-				continue;
272
-			}
273
-
274
-			if ($item instanceof Entity) {
275
-				$item = $item->getRawData();
276
-			}
277
-
278
-			if (is_array($item)) {
279
-				$item = json_encode($item);
280
-			}
281
-
282
-			$options['query'][$key] = $item;
283
-		}
284
-		unset($item);
285
-
286
-		if ($has_resource) {
287
-			$options['multipart'] = FormData::create($multipart);
288
-		}
289
-
290
-		return $options;
291
-	}
292
-
293
-	/**
294
-	 * Create a Http Request
295
-	 *
296
-	 * @param string $action Action to execute
297
-	 * @param array $data Data to attach to the execution
298
-	 *
299
-	 * @return array An array of the setUpRequestParams and the url
300
-	 */
301
-	public static function create(string $action, array $data): array
302
-	{
303
-		return [
304
-			'url' => self::getApiPath() . $action,
305
-			'options' => self::setUpRequestParams($data)
306
-		];
307
-	}
308
-
309
-	/**
310
-	 * Execute HTTP Request
311
-	 *
312
-	 * @param string $action Action to execute
313
-	 * @param array $data Data to attach to the execution
314
-	 *
315
-	 * @return string Result of the HTTP Request
316
-	 */
317
-	private static function execute(string $action, array $data): string
318
-	{
319
-		[$url, $options] = self::create($action, $data);
320
-
321
-		$response = self::getClient()->get($url, $options);
322
-
323
-		return $response->getBody();
324
-	}
325
-
326
-	/**
327
-	 * Send command
328
-	 *
329
-	 * @param string $action
330
-	 * @param array $data
331
-	 *
332
-	 * @return Response
333
-	 * @throws TelegramException
334
-	 */
335
-	public static function send(string $action, array $data = []): Response
336
-	{
337
-		self::$current_action = $action;
338
-
339
-		$raw_response = self::execute($action, $data);
340
-
341
-		if (!Common::isJson($raw_response)) {
342
-			TelegramLog::debug($raw_response);
343
-			throw new TelegramException('Invalid response from API');
344
-		}
345
-
346
-		$response = new Response(json_decode($raw_response, true));
347
-
348
-		if (!$response->isOk() && $response->getErrorCode() === 401 && $response->getDescription() === 'Unauthorized') {
349
-			throw new InvalidBotTokenException();
350
-		}
351
-
352
-		self::$current_action = '';
353
-
354
-		return $response;
355
-	}
356
-
357
-	/**
358
-	 * Any statically called method should be relayed to the `send` method.
359
-	 *
360
-	 * @param string $action
361
-	 * @param array $data
362
-	 *
363
-	 * @return Response
364
-	 * @throws TelegramException
365
-	 */
366
-	public static function __callStatic(string $action, array $data): Response
367
-	{
368
-		return static::send($action, reset($data) ?: []);
369
-	}
148
+    /**
149
+     * Available fields for InputFile helper
150
+     *
151
+     * This is basically the list of all fields that allow InputFile objects
152
+     * for which input can be simplified by providing local path directly  as string.
153
+     *
154
+     * @var array
155
+     */
156
+    private static array $input_file_fields = [
157
+        'setWebhook' => ['certificate'],
158
+        'sendPhoto' => ['photo'],
159
+        'sendAudio' => ['audio', 'thumb'],
160
+        'sendDocument' => ['document', 'thumb'],
161
+        'sendVideo' => ['video', 'thumb'],
162
+        'sendAnimation' => ['animation', 'thumb'],
163
+        'sendVoice' => ['voice', 'thumb'],
164
+        'sendVideoNote' => ['video_note', 'thumb'],
165
+        'setChatPhoto' => ['photo'],
166
+        'sendSticker' => ['sticker'],
167
+        'uploadStickerFile' => ['png_sticker'],
168
+        'createNewStickerSet' => ['png_sticker', 'tgs_sticker', 'webm_sticker'],
169
+        'addStickerToSet' => ['png_sticker', 'tgs_sticker', 'webm_sticker'],
170
+        'setStickerSetThumb' => ['thumb'],
171
+    ];
172
+
173
+    /**
174
+     * URI of the Telegram API
175
+     *
176
+     * @var string
177
+     */
178
+    private static string $api_base_uri = 'https://api.telegram.org';
179
+
180
+    /**
181
+     * URI of the Telegram API for downloading files (relative to $api_base_url or absolute)
182
+     *
183
+     * @var string
184
+     */
185
+    private static string $api_base_download_uri = '/file/bot{API_KEY}';
186
+
187
+    /**
188
+     * The current action that is being executed
189
+     *
190
+     * @var string
191
+     */
192
+    private static string $current_action = '';
193
+
194
+    /**
195
+     * Get the Telegram API path
196
+     *
197
+     * @return string
198
+     */
199
+    public static function getApiPath(): string
200
+    {
201
+        return self::$api_base_uri . '/bot' . Telegram::getApiKey() . '/';
202
+    }
203
+
204
+    /**
205
+     * Initialize a http client
206
+     *
207
+     * @return Client
208
+     */
209
+    private static function getClient(): Client
210
+    {
211
+        return new Client();
212
+    }
213
+
214
+    /**
215
+     * Use this method to get stats of given user in a supergroup or channel.
216
+     *
217
+     * @param int $user_id User identifier
218
+     * @param int $chat_id Identifier of the chat to get stats for
219
+     *
220
+     * @return string [left, member, administrator, creator]
221
+     */
222
+    public static function getChatMemberStatus(int $user_id, int $chat_id): string
223
+    {
224
+        $response = self::getChatMember([
225
+            'user_id' => $user_id,
226
+            'chat_id' => $chat_id,
227
+        ]);
228
+
229
+        return $response->getResult()->status ?? "left";
230
+    }
231
+
232
+    /**
233
+     * Properly set up the request params
234
+     *
235
+     * If any item of the array is a resource, reformat it to a multipart request.
236
+     * Else, just return the passed data as form params.
237
+     *
238
+     * @param array $data
239
+     * @return array
240
+     */
241
+    private static function setUpRequestParams(array $data): array
242
+    {
243
+        $multipart = [];
244
+        $has_resource = false;
245
+
246
+        $options = [
247
+            'header' => [
248
+                'Content-Type' => 'application/json',
249
+                'Accept' => 'application/json',
250
+                'User-Agent' => 'TelegramBot-PHP/' . Telegram::$VERSION
251
+            ]
252
+        ];
253
+
254
+        foreach ($data as $key => &$item) {
255
+            if (array_key_exists(self::$current_action, self::$input_file_fields) && in_array($key, self::$input_file_fields[self::$current_action], true)) {
256
+
257
+                if (is_string($item) && file_exists($item)) {
258
+                    $has_resource = true;
259
+
260
+                } elseif (filter_var($item, FILTER_VALIDATE_URL)) {
261
+                    $has_resource = false;
262
+                    continue;
263
+
264
+                } else {
265
+                    throw new TelegramException(
266
+                        'Invalid file path or URL: ' . $item . ' for ' . self::$current_action . ' action'
267
+                    );
268
+                }
269
+
270
+                $multipart[$key] = $item;
271
+                continue;
272
+            }
273
+
274
+            if ($item instanceof Entity) {
275
+                $item = $item->getRawData();
276
+            }
277
+
278
+            if (is_array($item)) {
279
+                $item = json_encode($item);
280
+            }
281
+
282
+            $options['query'][$key] = $item;
283
+        }
284
+        unset($item);
285
+
286
+        if ($has_resource) {
287
+            $options['multipart'] = FormData::create($multipart);
288
+        }
289
+
290
+        return $options;
291
+    }
292
+
293
+    /**
294
+     * Create a Http Request
295
+     *
296
+     * @param string $action Action to execute
297
+     * @param array $data Data to attach to the execution
298
+     *
299
+     * @return array An array of the setUpRequestParams and the url
300
+     */
301
+    public static function create(string $action, array $data): array
302
+    {
303
+        return [
304
+            'url' => self::getApiPath() . $action,
305
+            'options' => self::setUpRequestParams($data)
306
+        ];
307
+    }
308
+
309
+    /**
310
+     * Execute HTTP Request
311
+     *
312
+     * @param string $action Action to execute
313
+     * @param array $data Data to attach to the execution
314
+     *
315
+     * @return string Result of the HTTP Request
316
+     */
317
+    private static function execute(string $action, array $data): string
318
+    {
319
+        [$url, $options] = self::create($action, $data);
320
+
321
+        $response = self::getClient()->get($url, $options);
322
+
323
+        return $response->getBody();
324
+    }
325
+
326
+    /**
327
+     * Send command
328
+     *
329
+     * @param string $action
330
+     * @param array $data
331
+     *
332
+     * @return Response
333
+     * @throws TelegramException
334
+     */
335
+    public static function send(string $action, array $data = []): Response
336
+    {
337
+        self::$current_action = $action;
338
+
339
+        $raw_response = self::execute($action, $data);
340
+
341
+        if (!Common::isJson($raw_response)) {
342
+            TelegramLog::debug($raw_response);
343
+            throw new TelegramException('Invalid response from API');
344
+        }
345
+
346
+        $response = new Response(json_decode($raw_response, true));
347
+
348
+        if (!$response->isOk() && $response->getErrorCode() === 401 && $response->getDescription() === 'Unauthorized') {
349
+            throw new InvalidBotTokenException();
350
+        }
351
+
352
+        self::$current_action = '';
353
+
354
+        return $response;
355
+    }
356
+
357
+    /**
358
+     * Any statically called method should be relayed to the `send` method.
359
+     *
360
+     * @param string $action
361
+     * @param array $data
362
+     *
363
+     * @return Response
364
+     * @throws TelegramException
365
+     */
366
+    public static function __callStatic(string $action, array $data): Response
367
+    {
368
+        return static::send($action, reset($data) ?: []);
369
+    }
370 370
 
371 371
 }
Please login to merge, or discard this patch.
src/lib/Plugin.php 2 patches
Indentation   +74 added lines, -74 removed lines patch added patch discarded remove patch
@@ -15,88 +15,88 @@
 block discarded – undo
15 15
 abstract class Plugin
16 16
 {
17 17
 
18
-	/**
19
-	 * The Update types
20
-	 *
21
-	 * @var array
22
-	 */
23
-	protected array $update_types = [
24
-		'message',
25
-		'edited_message',
26
-		'channel_post',
27
-		'edited_channel_post',
28
-		'inline_query',
29
-		'chosen_inline_result',
30
-		'callback_query',
31
-		'shipping_query',
32
-		'pre_checkout_query',
33
-	];
18
+    /**
19
+     * The Update types
20
+     *
21
+     * @var array
22
+     */
23
+    protected array $update_types = [
24
+        'message',
25
+        'edited_message',
26
+        'channel_post',
27
+        'edited_channel_post',
28
+        'inline_query',
29
+        'chosen_inline_result',
30
+        'callback_query',
31
+        'shipping_query',
32
+        'pre_checkout_query',
33
+    ];
34 34
 
35
-	/**
36
-	 * @var WebhookHandler
37
-	 */
38
-	protected WebhookHandler $hook;
35
+    /**
36
+     * @var WebhookHandler
37
+     */
38
+    protected WebhookHandler $hook;
39 39
 
40
-	/**
41
-	 * @var \Generator
42
-	 */
43
-	protected \Generator $returns;
40
+    /**
41
+     * @var \Generator
42
+     */
43
+    protected \Generator $returns;
44 44
 
45
-	/**
46
-	 * @var bool
47
-	 */
48
-	protected bool $kill_on_yield = false;
45
+    /**
46
+     * @var bool
47
+     */
48
+    protected bool $kill_on_yield = false;
49 49
 
50
-	/**
51
-	 * Execute the plugin.
52
-	 *
53
-	 * @param WebhookHandler $receiver
54
-	 * @param Update $update
55
-	 * @return void
56
-	 */
57
-	public function __execute(WebhookHandler $receiver, Update $update): void
58
-	{
59
-		$this->hook = $receiver;
50
+    /**
51
+     * Execute the plugin.
52
+     *
53
+     * @param WebhookHandler $receiver
54
+     * @param Update $update
55
+     * @return void
56
+     */
57
+    public function __execute(WebhookHandler $receiver, Update $update): void
58
+    {
59
+        $this->hook = $receiver;
60 60
 
61
-		$method = 'onReceivedUpdate';
62
-		if (method_exists($this, $method)) {
63
-			/** @var \Generator $return */
64
-			$return = $this->{$method}($update);
65
-		}
61
+        $method = 'onReceivedUpdate';
62
+        if (method_exists($this, $method)) {
63
+            /** @var \Generator $return */
64
+            $return = $this->{$method}($update);
65
+        }
66 66
 
67
-		if (isset($return) && $return instanceof \Generator) {
68
-			while ($return->valid()) {
69
-				$return->next();
70
-			}
67
+        if (isset($return) && $return instanceof \Generator) {
68
+            while ($return->valid()) {
69
+                $return->next();
70
+            }
71 71
 
72
-			if ($return->valid() && $return->getReturn()) {
73
-				if ($this->kill_on_yield) $this->kill();
74
-			}
75
-		}
76
-	}
72
+            if ($return->valid() && $return->getReturn()) {
73
+                if ($this->kill_on_yield) $this->kill();
74
+            }
75
+        }
76
+    }
77 77
 
78
-	/**
79
-	 * Identify the update type and if method of the type is exists, execute it.
80
-	 *
81
-	 * @param Update $update
82
-	 * @return \Generator
83
-	 */
84
-	protected function onReceivedUpdate(Update $update): \Generator
85
-	{
86
-		$method = UpdateTypes::identify($update);
87
-		if (method_exists($this, $method)) {
88
-			yield $this->$method($update);
89
-		}
90
-	}
78
+    /**
79
+     * Identify the update type and if method of the type is exists, execute it.
80
+     *
81
+     * @param Update $update
82
+     * @return \Generator
83
+     */
84
+    protected function onReceivedUpdate(Update $update): \Generator
85
+    {
86
+        $method = UpdateTypes::identify($update);
87
+        if (method_exists($this, $method)) {
88
+            yield $this->$method($update);
89
+        }
90
+    }
91 91
 
92
-	/**
93
-	 * Kill the plugin.
94
-	 *
95
-	 * @return void
96
-	 */
97
-	public function kill(): void
98
-	{
99
-		$this->hook->kill();
100
-	}
92
+    /**
93
+     * Kill the plugin.
94
+     *
95
+     * @return void
96
+     */
97
+    public function kill(): void
98
+    {
99
+        $this->hook->kill();
100
+    }
101 101
 
102 102
 }
103 103
\ No newline at end of file
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -70,7 +70,9 @@
 block discarded – undo
70 70
 			}
71 71
 
72 72
 			if ($return->valid() && $return->getReturn()) {
73
-				if ($this->kill_on_yield) $this->kill();
73
+				if ($this->kill_on_yield) {
74
+				    $this->kill();
75
+				}
74 76
 			}
75 77
 		}
76 78
 	}
Please login to merge, or discard this patch.