Passed
Push — master ( c1a8c1...b5fef0 )
by Shahrad
02:24
created
src/lib/TelegramLog.php 2 patches
Indentation   +137 added lines, -137 removed lines patch added patch discarded remove patch
@@ -25,142 +25,142 @@
 block discarded – undo
25 25
 class TelegramLog
26 26
 {
27 27
 
28
-	/**
29
-	 * Logger instance
30
-	 *
31
-	 * @var LoggerInterface
32
-	 */
33
-	protected static LoggerInterface $logger;
34
-
35
-	/**
36
-	 * Logger instance for update
37
-	 *
38
-	 * @var LoggerInterface
39
-	 */
40
-	protected static LoggerInterface $update_logger;
41
-
42
-	/**
43
-	 * Always log the request and response data to the debug log, also for successful requests
44
-	 *
45
-	 * @var bool
46
-	 */
47
-	public static bool $always_log_request_and_response = false;
48
-
49
-	/**
50
-	 * Temporary stream handle for debug log
51
-	 *
52
-	 * @var resource|null
53
-	 */
54
-	protected static $debug_log_temp_stream_handle;
55
-
56
-	/**
57
-	 * Remove bot token from debug stream
58
-	 *
59
-	 * @var bool
60
-	 */
61
-	public static bool $remove_bot_token = true;
62
-
63
-	/**
64
-	 * Initialise logging.
65
-	 *
66
-	 * @param LoggerInterface|null $logger
67
-	 * @param LoggerInterface|null $update_logger
68
-	 */
69
-	public static function initialize(LoggerInterface $logger = null, LoggerInterface $update_logger = null): void
70
-	{
71
-		self::$logger = $logger ?: new NullLogger();
72
-		self::$update_logger = $update_logger ?: new NullLogger();
73
-	}
74
-
75
-	/**
76
-	 * Get the stream handle of the temporary debug output
77
-	 *
78
-	 * @return mixed The stream if debug is active, else false
79
-	 */
80
-	public static function getDebugLogTempStream(): mixed
81
-	{
82
-		if ((self::$debug_log_temp_stream_handle === null) && $temp_stream_handle = fopen('php://temp', 'wb+')) {
83
-			self::$debug_log_temp_stream_handle = $temp_stream_handle;
84
-		}
85
-
86
-		return self::$debug_log_temp_stream_handle;
87
-	}
88
-
89
-	/**
90
-	 * Write the temporary debug stream to log and close the stream handle
91
-	 *
92
-	 * @param string $message Message (with placeholder) to write to the debug log
93
-	 */
94
-	public static function endDebugLogTempStream(string $message = '%s'): void
95
-	{
96
-		if (is_resource(self::$debug_log_temp_stream_handle)) {
97
-			rewind(self::$debug_log_temp_stream_handle);
98
-			$stream_contents = stream_get_contents(self::$debug_log_temp_stream_handle);
99
-
100
-			if (self::$remove_bot_token) {
101
-				$stream_contents = preg_replace('/\/bot(\d+):[\w\-]+\//', '/botBOT_TOKEN_REMOVED/', $stream_contents);
102
-			}
103
-
104
-			self::debug(sprintf($message, $stream_contents));
105
-			fclose(self::$debug_log_temp_stream_handle);
106
-			self::$debug_log_temp_stream_handle = null;
107
-		}
108
-	}
109
-
110
-	/**
111
-	 * Handle any logging method call.
112
-	 *
113
-	 * @param string $name
114
-	 * @param array $arguments
115
-	 */
116
-	public static function __callStatic(string $name, array $arguments)
117
-	{
118
-		// Get the correct logger instance.
119
-		$logger = null;
120
-		self::initialize();
121
-		if (in_array($name, ['emergency', 'alert', 'critical', 'error', 'warning', 'notice', 'info', 'debug',], true)) {
122
-			$logger = self::$logger;
123
-		} elseif ($name === 'update') {
124
-			$logger = self::$update_logger;
125
-			$name = 'info';
126
-		}
127
-
128
-		// Clearly we have no logging enabled.
129
-		if ($logger === null) {
130
-			return;
131
-		}
132
-
133
-		// Replace any placeholders from the passed context.
134
-		if (count($arguments) >= 2) {
135
-			$arguments[0] = self::interpolate($arguments[0], $arguments[1]);
136
-		}
137
-
138
-		call_user_func_array([$logger, $name], $arguments);
139
-	}
140
-
141
-	/**
142
-	 * Interpolates context values into the message placeholders.
143
-	 *
144
-	 * @see https://www.php-fig.org/psr/psr-3/#12-message
145
-	 *
146
-	 * @param string $message
147
-	 * @param array $context
148
-	 *
149
-	 * @return string
150
-	 */
151
-	protected static function interpolate(string $message, array $context = []): string
152
-	{
153
-		// Build a replacement array with braces around the context keys.
154
-		$replace = [];
155
-		foreach ($context as $key => $val) {
156
-			// check that the value can be cast to string
157
-			if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString'))) {
158
-				$replace["{{$key}}"] = $val;
159
-			}
160
-		}
161
-
162
-		// Interpolate replacement values into the message and return.
163
-		return strtr($message, $replace);
164
-	}
28
+    /**
29
+     * Logger instance
30
+     *
31
+     * @var LoggerInterface
32
+     */
33
+    protected static LoggerInterface $logger;
34
+
35
+    /**
36
+     * Logger instance for update
37
+     *
38
+     * @var LoggerInterface
39
+     */
40
+    protected static LoggerInterface $update_logger;
41
+
42
+    /**
43
+     * Always log the request and response data to the debug log, also for successful requests
44
+     *
45
+     * @var bool
46
+     */
47
+    public static bool $always_log_request_and_response = false;
48
+
49
+    /**
50
+     * Temporary stream handle for debug log
51
+     *
52
+     * @var resource|null
53
+     */
54
+    protected static $debug_log_temp_stream_handle;
55
+
56
+    /**
57
+     * Remove bot token from debug stream
58
+     *
59
+     * @var bool
60
+     */
61
+    public static bool $remove_bot_token = true;
62
+
63
+    /**
64
+     * Initialise logging.
65
+     *
66
+     * @param LoggerInterface|null $logger
67
+     * @param LoggerInterface|null $update_logger
68
+     */
69
+    public static function initialize(LoggerInterface $logger = null, LoggerInterface $update_logger = null): void
70
+    {
71
+        self::$logger = $logger ?: new NullLogger();
72
+        self::$update_logger = $update_logger ?: new NullLogger();
73
+    }
74
+
75
+    /**
76
+     * Get the stream handle of the temporary debug output
77
+     *
78
+     * @return mixed The stream if debug is active, else false
79
+     */
80
+    public static function getDebugLogTempStream(): mixed
81
+    {
82
+        if ((self::$debug_log_temp_stream_handle === null) && $temp_stream_handle = fopen('php://temp', 'wb+')) {
83
+            self::$debug_log_temp_stream_handle = $temp_stream_handle;
84
+        }
85
+
86
+        return self::$debug_log_temp_stream_handle;
87
+    }
88
+
89
+    /**
90
+     * Write the temporary debug stream to log and close the stream handle
91
+     *
92
+     * @param string $message Message (with placeholder) to write to the debug log
93
+     */
94
+    public static function endDebugLogTempStream(string $message = '%s'): void
95
+    {
96
+        if (is_resource(self::$debug_log_temp_stream_handle)) {
97
+            rewind(self::$debug_log_temp_stream_handle);
98
+            $stream_contents = stream_get_contents(self::$debug_log_temp_stream_handle);
99
+
100
+            if (self::$remove_bot_token) {
101
+                $stream_contents = preg_replace('/\/bot(\d+):[\w\-]+\//', '/botBOT_TOKEN_REMOVED/', $stream_contents);
102
+            }
103
+
104
+            self::debug(sprintf($message, $stream_contents));
105
+            fclose(self::$debug_log_temp_stream_handle);
106
+            self::$debug_log_temp_stream_handle = null;
107
+        }
108
+    }
109
+
110
+    /**
111
+     * Handle any logging method call.
112
+     *
113
+     * @param string $name
114
+     * @param array $arguments
115
+     */
116
+    public static function __callStatic(string $name, array $arguments)
117
+    {
118
+        // Get the correct logger instance.
119
+        $logger = null;
120
+        self::initialize();
121
+        if (in_array($name, ['emergency', 'alert', 'critical', 'error', 'warning', 'notice', 'info', 'debug',], true)) {
122
+            $logger = self::$logger;
123
+        } elseif ($name === 'update') {
124
+            $logger = self::$update_logger;
125
+            $name = 'info';
126
+        }
127
+
128
+        // Clearly we have no logging enabled.
129
+        if ($logger === null) {
130
+            return;
131
+        }
132
+
133
+        // Replace any placeholders from the passed context.
134
+        if (count($arguments) >= 2) {
135
+            $arguments[0] = self::interpolate($arguments[0], $arguments[1]);
136
+        }
137
+
138
+        call_user_func_array([$logger, $name], $arguments);
139
+    }
140
+
141
+    /**
142
+     * Interpolates context values into the message placeholders.
143
+     *
144
+     * @see https://www.php-fig.org/psr/psr-3/#12-message
145
+     *
146
+     * @param string $message
147
+     * @param array $context
148
+     *
149
+     * @return string
150
+     */
151
+    protected static function interpolate(string $message, array $context = []): string
152
+    {
153
+        // Build a replacement array with braces around the context keys.
154
+        $replace = [];
155
+        foreach ($context as $key => $val) {
156
+            // check that the value can be cast to string
157
+            if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString'))) {
158
+                $replace["{{$key}}"] = $val;
159
+            }
160
+        }
161
+
162
+        // Interpolate replacement values into the message and return.
163
+        return strtr($message, $replace);
164
+    }
165 165
 
166 166
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -118,7 +118,7 @@
 block discarded – undo
118 118
 		// Get the correct logger instance.
119 119
 		$logger = null;
120 120
 		self::initialize();
121
-		if (in_array($name, ['emergency', 'alert', 'critical', 'error', 'warning', 'notice', 'info', 'debug',], true)) {
121
+		if (in_array($name, ['emergency', 'alert', 'critical', 'error', 'warning', 'notice', 'info', 'debug', ], true)) {
122 122
 			$logger = self::$logger;
123 123
 		} elseif ($name === 'update') {
124 124
 			$logger = self::$update_logger;
Please login to merge, or discard this patch.
src/lib/Factory.php 1 patch
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -12,26 +12,26 @@
 block discarded – undo
12 12
 abstract class Factory
13 13
 {
14 14
 
15
-	/**
16
-	 * @param array $data
17
-	 * @return Entity
18
-	 */
19
-	abstract public static function make(array $data): Entity;
15
+    /**
16
+     * @param array $data
17
+     * @return Entity
18
+     */
19
+    abstract public static function make(array $data): Entity;
20 20
 
21
-	/**
22
-	 * This method is used to create a new instance of the entity.
23
-	 *
24
-	 * @param string $class
25
-	 * @param mixed $property
26
-	 * @return Entity
27
-	 */
28
-	public static function resolveEntityClass(string $class, mixed $property): Entity
29
-	{
30
-		if (is_subclass_of($class, Factory::class)) {
31
-			return $class::make($property);
32
-		}
21
+    /**
22
+     * This method is used to create a new instance of the entity.
23
+     *
24
+     * @param string $class
25
+     * @param mixed $property
26
+     * @return Entity
27
+     */
28
+    public static function resolveEntityClass(string $class, mixed $property): Entity
29
+    {
30
+        if (is_subclass_of($class, Factory::class)) {
31
+            return $class::make($property);
32
+        }
33 33
 
34
-		return new $class($property);
35
-	}
34
+        return new $class($property);
35
+    }
36 36
 
37 37
 }
Please login to merge, or discard this patch.
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.
src/lib/Entities/Keyboard.php 1 patch
Indentation   +98 added lines, -98 removed lines patch added patch discarded remove patch
@@ -23,103 +23,103 @@
 block discarded – undo
23 23
 class Keyboard extends Entity
24 24
 {
25 25
 
26
-	public function __construct(array $data = [])
27
-	{
28
-		parent::__construct(array_merge($data, [
29
-			'resize_keyboard' => false,
30
-			'one_time_keyboard' => false,
31
-			'input_field_placeholder' => '',
32
-			'selective' => false
33
-		]));
34
-	}
35
-
36
-	/**
37
-	 * Create a new row in keyboard and add buttons.
38
-	 *
39
-	 * @param array<KeyboardButton> $row
40
-	 * @return Keyboard
41
-	 */
42
-	public function addRow(array $row): Keyboard
43
-	{
44
-		$keyboard_type = self::getType();
45
-
46
-		if (!isset($this->raw_data[$keyboard_type]) || !is_array($this->raw_data[$keyboard_type])) {
47
-			$this->raw_data[$keyboard_type] = [];
48
-		}
49
-
50
-		$new_row = [];
51
-		foreach ($row as $button) {
52
-			$new_row[] = $button->getRawData();
53
-		}
54
-
55
-		$this->raw_data[$keyboard_type][] = $new_row;
56
-
57
-		return $this;
58
-	}
59
-
60
-	/**
61
-	 * Remove the current custom keyboard and display the default letter-keyboard.
62
-	 *
63
-	 * @link https://core.telegram.org/bots/api/#replykeyboardremove
64
-	 *
65
-	 * @param array $data
66
-	 *
67
-	 * @return Keyboard
68
-	 */
69
-	public static function remove(array $data = []): Keyboard
70
-	{
71
-		return new static(array_merge(['keyboard' => [], 'remove_keyboard' => true, 'selective' => false], $data));
72
-	}
73
-
74
-	/**
75
-	 * Display a reply interface to the user (act as if the user has selected the bot's message and tapped 'Reply').
76
-	 *
77
-	 * @link https://core.telegram.org/bots/api#forcereply
78
-	 *
79
-	 * @param array $data
80
-	 *
81
-	 * @return Keyboard
82
-	 */
83
-	public static function forceReply(array $data = []): Keyboard
84
-	{
85
-		return new static(array_merge(['keyboard' => [], 'force_reply' => true, 'selective' => false], $data));
86
-	}
87
-
88
-	/**
89
-	 * Get keyboard button type
90
-	 *
91
-	 * @return string ["keyboard"|"inline_keyboard"]
92
-	 */
93
-	public function getType(): string
94
-	{
95
-		$reflection = new \ReflectionClass(static::class);
96
-
97
-		$class_name = $reflection->getShortName();
98
-
99
-		return strtolower(ltrim(preg_replace('/[A-Z]/', '_$0', $class_name), '_'));
100
-	}
101
-
102
-	/**
103
-	 * Creates instance of Keyboard
104
-	 *
105
-	 * @return Keyboard
106
-	 */
107
-	public static function make(): Keyboard
108
-	{
109
-		return new self();
110
-	}
111
-
112
-	/**
113
-	 * @param array $rows
114
-	 * @return Keyboard
115
-	 */
116
-	public function setKeyboard(array $rows): Keyboard
117
-	{
118
-		foreach ($rows as $row) {
119
-			$this->addRow($row);
120
-		}
121
-
122
-		return $this;
123
-	}
26
+    public function __construct(array $data = [])
27
+    {
28
+        parent::__construct(array_merge($data, [
29
+            'resize_keyboard' => false,
30
+            'one_time_keyboard' => false,
31
+            'input_field_placeholder' => '',
32
+            'selective' => false
33
+        ]));
34
+    }
35
+
36
+    /**
37
+     * Create a new row in keyboard and add buttons.
38
+     *
39
+     * @param array<KeyboardButton> $row
40
+     * @return Keyboard
41
+     */
42
+    public function addRow(array $row): Keyboard
43
+    {
44
+        $keyboard_type = self::getType();
45
+
46
+        if (!isset($this->raw_data[$keyboard_type]) || !is_array($this->raw_data[$keyboard_type])) {
47
+            $this->raw_data[$keyboard_type] = [];
48
+        }
49
+
50
+        $new_row = [];
51
+        foreach ($row as $button) {
52
+            $new_row[] = $button->getRawData();
53
+        }
54
+
55
+        $this->raw_data[$keyboard_type][] = $new_row;
56
+
57
+        return $this;
58
+    }
59
+
60
+    /**
61
+     * Remove the current custom keyboard and display the default letter-keyboard.
62
+     *
63
+     * @link https://core.telegram.org/bots/api/#replykeyboardremove
64
+     *
65
+     * @param array $data
66
+     *
67
+     * @return Keyboard
68
+     */
69
+    public static function remove(array $data = []): Keyboard
70
+    {
71
+        return new static(array_merge(['keyboard' => [], 'remove_keyboard' => true, 'selective' => false], $data));
72
+    }
73
+
74
+    /**
75
+     * Display a reply interface to the user (act as if the user has selected the bot's message and tapped 'Reply').
76
+     *
77
+     * @link https://core.telegram.org/bots/api#forcereply
78
+     *
79
+     * @param array $data
80
+     *
81
+     * @return Keyboard
82
+     */
83
+    public static function forceReply(array $data = []): Keyboard
84
+    {
85
+        return new static(array_merge(['keyboard' => [], 'force_reply' => true, 'selective' => false], $data));
86
+    }
87
+
88
+    /**
89
+     * Get keyboard button type
90
+     *
91
+     * @return string ["keyboard"|"inline_keyboard"]
92
+     */
93
+    public function getType(): string
94
+    {
95
+        $reflection = new \ReflectionClass(static::class);
96
+
97
+        $class_name = $reflection->getShortName();
98
+
99
+        return strtolower(ltrim(preg_replace('/[A-Z]/', '_$0', $class_name), '_'));
100
+    }
101
+
102
+    /**
103
+     * Creates instance of Keyboard
104
+     *
105
+     * @return Keyboard
106
+     */
107
+    public static function make(): Keyboard
108
+    {
109
+        return new self();
110
+    }
111
+
112
+    /**
113
+     * @param array $rows
114
+     * @return Keyboard
115
+     */
116
+    public function setKeyboard(array $rows): Keyboard
117
+    {
118
+        foreach ($rows as $row) {
119
+            $this->addRow($row);
120
+        }
121
+
122
+        return $this;
123
+    }
124 124
 
125 125
 }
Please login to merge, or discard this patch.
src/lib/Entities/Update.php 1 patch
Indentation   +61 added lines, -61 removed lines patch added patch discarded remove patch
@@ -32,70 +32,70 @@
 block discarded – undo
32 32
 class Update extends Entity
33 33
 {
34 34
 
35
-	public const TYPE_MESSAGE = 'message';
36
-	public const TYPE_EDITED_MESSAGE = 'edited_message';
37
-	public const TYPE_CHANNEL_POST = 'channel_post';
38
-	public const TYPE_EDITED_CHANNEL_POST = 'edited_channel_post';
39
-	public const TYPE_INLINE_QUERY = 'inline_query';
40
-	public const TYPE_CHOSEN_INLINE_RESULT = 'chosen_inline_result';
41
-	public const TYPE_CALLBACK_QUERY = 'callback_query';
42
-	public const TYPE_SHIPPING_QUERY = 'shipping_query';
43
-	public const TYPE_PRE_CHECKOUT_QUERY = 'pre_checkout_query';
44
-	public const TYPE_POLL = 'poll';
45
-	public const TYPE_POLL_ANSWER = 'poll_answer';
46
-	public const TYPE_MY_CHAT_MEMBER = 'my_chat_member';
47
-	public const TYPE_CHAT_MEMBER = 'chat_member';
48
-	public const TYPE_CHAT_JOIN_REQUEST = 'chat_join_request';
49
-	public const TYPE_WEB_DATA = 'web_data';
35
+    public const TYPE_MESSAGE = 'message';
36
+    public const TYPE_EDITED_MESSAGE = 'edited_message';
37
+    public const TYPE_CHANNEL_POST = 'channel_post';
38
+    public const TYPE_EDITED_CHANNEL_POST = 'edited_channel_post';
39
+    public const TYPE_INLINE_QUERY = 'inline_query';
40
+    public const TYPE_CHOSEN_INLINE_RESULT = 'chosen_inline_result';
41
+    public const TYPE_CALLBACK_QUERY = 'callback_query';
42
+    public const TYPE_SHIPPING_QUERY = 'shipping_query';
43
+    public const TYPE_PRE_CHECKOUT_QUERY = 'pre_checkout_query';
44
+    public const TYPE_POLL = 'poll';
45
+    public const TYPE_POLL_ANSWER = 'poll_answer';
46
+    public const TYPE_MY_CHAT_MEMBER = 'my_chat_member';
47
+    public const TYPE_CHAT_MEMBER = 'chat_member';
48
+    public const TYPE_CHAT_JOIN_REQUEST = 'chat_join_request';
49
+    public const TYPE_WEB_DATA = 'web_data';
50 50
 
51
-	/**
52
-	 * {@inheritdoc}
53
-	 */
54
-	protected function subEntities(): array
55
-	{
56
-		return [
57
-			self::TYPE_MESSAGE => Message::class,
58
-			self::TYPE_EDITED_MESSAGE => EditedMessage::class,
59
-			self::TYPE_CHANNEL_POST => ChannelPost::class,
60
-			self::TYPE_EDITED_CHANNEL_POST => EditedChannelPost::class,
61
-			self::TYPE_INLINE_QUERY => InlineQuery::class,
62
-			self::TYPE_CHOSEN_INLINE_RESULT => ChosenInlineResult::class,
63
-			self::TYPE_CALLBACK_QUERY => CallbackQuery::class,
64
-			self::TYPE_SHIPPING_QUERY => ShippingQuery::class,
65
-			self::TYPE_PRE_CHECKOUT_QUERY => PreCheckoutQuery::class,
66
-			self::TYPE_POLL => Poll::class,
67
-			self::TYPE_POLL_ANSWER => PollAnswer::class,
68
-			self::TYPE_MY_CHAT_MEMBER => ChatMemberUpdated::class,
69
-			self::TYPE_CHAT_MEMBER => ChatMemberUpdated::class,
70
-			self::TYPE_CHAT_JOIN_REQUEST => ChatJoinRequest::class,
71
-			self::TYPE_WEB_DATA => WebAppData::class,
72
-		];
73
-	}
51
+    /**
52
+     * {@inheritdoc}
53
+     */
54
+    protected function subEntities(): array
55
+    {
56
+        return [
57
+            self::TYPE_MESSAGE => Message::class,
58
+            self::TYPE_EDITED_MESSAGE => EditedMessage::class,
59
+            self::TYPE_CHANNEL_POST => ChannelPost::class,
60
+            self::TYPE_EDITED_CHANNEL_POST => EditedChannelPost::class,
61
+            self::TYPE_INLINE_QUERY => InlineQuery::class,
62
+            self::TYPE_CHOSEN_INLINE_RESULT => ChosenInlineResult::class,
63
+            self::TYPE_CALLBACK_QUERY => CallbackQuery::class,
64
+            self::TYPE_SHIPPING_QUERY => ShippingQuery::class,
65
+            self::TYPE_PRE_CHECKOUT_QUERY => PreCheckoutQuery::class,
66
+            self::TYPE_POLL => Poll::class,
67
+            self::TYPE_POLL_ANSWER => PollAnswer::class,
68
+            self::TYPE_MY_CHAT_MEMBER => ChatMemberUpdated::class,
69
+            self::TYPE_CHAT_MEMBER => ChatMemberUpdated::class,
70
+            self::TYPE_CHAT_JOIN_REQUEST => ChatJoinRequest::class,
71
+            self::TYPE_WEB_DATA => WebAppData::class,
72
+        ];
73
+    }
74 74
 
75
-	/**
76
-	 * Get the list of all available update types
77
-	 *
78
-	 * @return string[]
79
-	 */
80
-	public static function getUpdateTypes(): array
81
-	{
82
-		return array_keys((new self([]))->subEntities());
83
-	}
75
+    /**
76
+     * Get the list of all available update types
77
+     *
78
+     * @return string[]
79
+     */
80
+    public static function getUpdateTypes(): array
81
+    {
82
+        return array_keys((new self([]))->subEntities());
83
+    }
84 84
 
85
-	/**
86
-	 * Get the update type based on the set properties
87
-	 *
88
-	 * @return string|null
89
-	 */
90
-	public function getUpdateType(): ?string
91
-	{
92
-		foreach (self::getUpdateTypes() as $type) {
93
-			if ($this->getProperty($type)) {
94
-				return $type;
95
-			}
96
-		}
85
+    /**
86
+     * Get the update type based on the set properties
87
+     *
88
+     * @return string|null
89
+     */
90
+    public function getUpdateType(): ?string
91
+    {
92
+        foreach (self::getUpdateTypes() as $type) {
93
+            if ($this->getProperty($type)) {
94
+                return $type;
95
+            }
96
+        }
97 97
 
98
-		return null;
99
-	}
98
+        return null;
99
+    }
100 100
 
101 101
 }
Please login to merge, or discard this patch.
src/lib/WebhookHandler.php 2 patches
Braces   +11 added lines, -4 removed lines patch added patch discarded remove patch
@@ -156,10 +156,15 @@  discard block
 block discarded – undo
156 156
 			throw new \RuntimeException(sprintf('The method %s does not exist', $method));
157 157
 		}
158 158
 
159
-		if (is_array($config)) $this->updateConfiguration($config);
159
+		if (is_array($config)) {
160
+		    $this->updateConfiguration($config);
161
+		}
160 162
 
161
-		if (!empty($update)) $this->update = $update;
162
-		else $this->update = Telegram::getUpdate() !== false ? Telegram::getUpdate() : null;
163
+		if (!empty($update)) {
164
+		    $this->update = $update;
165
+		} else {
166
+		    $this->update = Telegram::getUpdate() !== false ? Telegram::getUpdate() : null;
167
+		}
163 168
 
164 169
 		if (empty($this->update)) {
165 170
 			TelegramLog::error(
@@ -211,7 +216,9 @@  discard block
 block discarded – undo
211 216
 		foreach ($plugins as $plugin) {
212 217
 			/** @var Plugin $plugin */
213 218
 			(new $plugin())->__execute($this, $update);
214
-			if ($this->isActive === false) break;
219
+			if ($this->isActive === false) {
220
+			    break;
221
+			}
215 222
 		}
216 223
 
217 224
 		$this->isActive = false;
Please login to merge, or discard this patch.
Indentation   +240 added lines, -240 removed lines patch added patch discarded remove patch
@@ -18,245 +18,245 @@
 block discarded – undo
18 18
 abstract class WebhookHandler extends Telegram
19 19
 {
20 20
 
21
-	/**
22
-	 * @var ?Update
23
-	 */
24
-	protected ?Update $update;
25
-
26
-	/**
27
-	 * @var array<Plugin>
28
-	 */
29
-	private array $plugins = [];
30
-
31
-	/**
32
-	 * @var bool
33
-	 */
34
-	private bool $isActive = false;
35
-
36
-	/**
37
-	 * The default configuration of the webhook.
38
-	 *
39
-	 * @var array
40
-	 */
41
-	private array $config = [
42
-		'autoload_env_file' => false,
43
-		'env_file_path' => null,
44
-	];
45
-
46
-	/**
47
-	 * Webhook constructor.
48
-	 *
49
-	 * @param string $api_key The API key of the bot. Leave it blank for autoload from .env file.
50
-	 */
51
-	public function __construct(string $api_key = '')
52
-	{
53
-		parent::__construct($api_key);
54
-
55
-		if (!Telegram::validateToken(self::getApiKey())) {
56
-			throw new InvalidBotTokenException();
57
-		}
58
-	}
59
-
60
-	/**
61
-	 * Initialize the receiver.
62
-	 *
63
-	 * @return void
64
-	 */
65
-	public function init(): void
66
-	{
67
-		$this->config['env_file_path'] = $_SERVER['DOCUMENT_ROOT'] . '/.env';
68
-	}
69
-
70
-	/**
71
-	 * Add a plugin to the receiver
72
-	 *
73
-	 * @param array<Plugin> $plugins
74
-	 */
75
-	public function addPlugin(array $plugins): void
76
-	{
77
-		foreach ($plugins as $plugin) {
78
-			if (!is_subclass_of($plugin, Plugin::class)) {
79
-				throw new \RuntimeException(
80
-					sprintf('The plugin %s must be an instance of %s', get_class($plugin), Plugin::class)
81
-				);
82
-			}
83
-			$this->plugins[] = $plugin;
84
-		}
85
-	}
86
-
87
-	/**
88
-	 * Match the update with the given plugins
89
-	 *
90
-	 * @param array<Plugin> $plugins
91
-	 * @param ?Update $update The update to match
92
-	 * @return void
93
-	 */
94
-	public function loadPluginsWith(array $plugins, Update $update = null): void
95
-	{
96
-		$update = $update ?? ($this->update ?? Telegram::getUpdate());
97
-
98
-		foreach ($plugins as $plugin) {
99
-			if (!is_subclass_of($plugin, Plugin::class)) {
100
-				throw new \InvalidArgumentException(
101
-					sprintf('The plugin %s must be an instance of %s', get_class($plugin), Plugin::class)
102
-				);
103
-			}
104
-		}
105
-
106
-		if ($update instanceof Update) {
107
-			$this->spreadUpdateWith($update, $plugins);
108
-		}
109
-	}
110
-
111
-	/**
112
-	 * Match the message to the plugins
113
-	 *
114
-	 * @param ?Update $update The update to match
115
-	 * @return void
116
-	 */
117
-	public function loadPlugins(Update $update = null): void
118
-	{
119
-		$update = $update ?? ($this->update ?? Telegram::getUpdate());
120
-		$this->loadPluginsWith($this->plugins, $update);
121
-	}
122
-
123
-	/**
124
-	 * Load the environment's
125
-	 *
126
-	 * @param string $path
127
-	 * @retrun void
128
-	 */
129
-	public function loadFileOfEnv(string $path): void
130
-	{
131
-		DotEnv::load($path);
132
-	}
133
-
134
-	/**
135
-	 * Update the configuration
136
-	 *
137
-	 * @param array $configuration
138
-	 * @return void
139
-	 */
140
-	public function updateConfiguration(array $configuration): void
141
-	{
142
-		$this->config = array_merge($this->config, $configuration);
143
-	}
144
-
145
-	/**
146
-	 * Resolve the request.
147
-	 *
148
-	 * @param ?Update $update The custom to work with
149
-	 * @param array $config The configuration of the receiver
150
-	 *
151
-	 * @retrun void
152
-	 */
153
-	public function resolve(Update $update = null, array $config = []): void
154
-	{
155
-		$method = '__process';
156
-		if (!method_exists($this, $method)) {
157
-			throw new \RuntimeException(sprintf('The method %s does not exist', $method));
158
-		}
159
-
160
-		if (is_array($config)) $this->updateConfiguration($config);
161
-
162
-		if (!empty($update)) $this->update = $update;
163
-		else $this->update = Telegram::getUpdate() !== false ? Telegram::getUpdate() : null;
164
-
165
-		if (empty($this->update)) {
166
-			TelegramLog::error(
167
-				'The update is empty, the request is not processed'
168
-			);
169
-			return;
170
-		}
171
-
172
-		try {
173
-
174
-			Common::arrest($this, $method, $this->update);
175
-
176
-		} catch (\RuntimeException $exception) {
177
-
178
-			$e = $exception->getPrevious();
179
-			TelegramLog::error(($message = sprintf(
180
-				'%s(%d): %s\n%s', $e->getFile(), $e->getLine(), $e->getMessage(), $e->getTraceAsString()
181
-			)));
182
-
183
-			if (defined('TG_ADMIN_ID') && TG_ADMIN_ID && defined('DEBUG_MODE') && DEBUG_MODE) {
184
-				file_put_contents(
185
-					($file = getcwd() . '/' . uniqid('error_') . '.log'),
186
-					$message . PHP_EOL . PHP_EOL . $update->getRawData(false)
187
-				);
188
-				Request::sendMessage([
189
-					'chat_id' => TG_ADMIN_ID,
190
-					'text' => $message,
191
-				]);
192
-				Request::sendDocument([
193
-					'chat_id' => TG_ADMIN_ID,
194
-					'document' => $file,
195
-				]);
196
-				unlink($file);
197
-			}
198
-		}
199
-	}
200
-
201
-	/**
202
-	 * This function will get update and spread it to the plugins
203
-	 *
204
-	 * @param Update $update
205
-	 * @param array<Plugin> $plugins
206
-	 * @return void
207
-	 */
208
-	private function spreadUpdateWith(Update $update, array $plugins): void
209
-	{
210
-		$this->isActive = true;
211
-
212
-		foreach ($plugins as $plugin) {
213
-			/** @var Plugin $plugin */
214
-			(new $plugin())->__execute($this, $update);
215
-			if ($this->isActive === false) break;
216
-		}
217
-
218
-		$this->isActive = false;
219
-	}
220
-
221
-	/**
222
-	 * Kill the speeding process
223
-	 *
224
-	 * @return void
225
-	 */
226
-	public function kill(): void
227
-	{
228
-		$this->isActive = false;
229
-	}
230
-
231
-	/**
232
-	 * Use this method on the webhook class to get the updates
233
-	 *
234
-	 * @param Update $update
235
-	 * @return void
236
-	 */
237
-	abstract public function __process(Update $update): void;
238
-
239
-	/**
240
-	 * put CrossData into the plugins
241
-	 *
242
-	 * @param string $key
243
-	 * @param mixed $value
244
-	 * @return void
245
-	 */
246
-	public function putCrossData(string $key, mixed $value): void
247
-	{
248
-		CrossData::put($key, $value);
249
-	}
250
-
251
-	/**
252
-	 * get CrossData from the plugins
253
-	 *
254
-	 * @param string $key
255
-	 * @return string|array|bool|null
256
-	 */
257
-	public function getCrossData(string $key): string|array|bool|null
258
-	{
259
-		return CrossData::get($key);
260
-	}
21
+    /**
22
+     * @var ?Update
23
+     */
24
+    protected ?Update $update;
25
+
26
+    /**
27
+     * @var array<Plugin>
28
+     */
29
+    private array $plugins = [];
30
+
31
+    /**
32
+     * @var bool
33
+     */
34
+    private bool $isActive = false;
35
+
36
+    /**
37
+     * The default configuration of the webhook.
38
+     *
39
+     * @var array
40
+     */
41
+    private array $config = [
42
+        'autoload_env_file' => false,
43
+        'env_file_path' => null,
44
+    ];
45
+
46
+    /**
47
+     * Webhook constructor.
48
+     *
49
+     * @param string $api_key The API key of the bot. Leave it blank for autoload from .env file.
50
+     */
51
+    public function __construct(string $api_key = '')
52
+    {
53
+        parent::__construct($api_key);
54
+
55
+        if (!Telegram::validateToken(self::getApiKey())) {
56
+            throw new InvalidBotTokenException();
57
+        }
58
+    }
59
+
60
+    /**
61
+     * Initialize the receiver.
62
+     *
63
+     * @return void
64
+     */
65
+    public function init(): void
66
+    {
67
+        $this->config['env_file_path'] = $_SERVER['DOCUMENT_ROOT'] . '/.env';
68
+    }
69
+
70
+    /**
71
+     * Add a plugin to the receiver
72
+     *
73
+     * @param array<Plugin> $plugins
74
+     */
75
+    public function addPlugin(array $plugins): void
76
+    {
77
+        foreach ($plugins as $plugin) {
78
+            if (!is_subclass_of($plugin, Plugin::class)) {
79
+                throw new \RuntimeException(
80
+                    sprintf('The plugin %s must be an instance of %s', get_class($plugin), Plugin::class)
81
+                );
82
+            }
83
+            $this->plugins[] = $plugin;
84
+        }
85
+    }
86
+
87
+    /**
88
+     * Match the update with the given plugins
89
+     *
90
+     * @param array<Plugin> $plugins
91
+     * @param ?Update $update The update to match
92
+     * @return void
93
+     */
94
+    public function loadPluginsWith(array $plugins, Update $update = null): void
95
+    {
96
+        $update = $update ?? ($this->update ?? Telegram::getUpdate());
97
+
98
+        foreach ($plugins as $plugin) {
99
+            if (!is_subclass_of($plugin, Plugin::class)) {
100
+                throw new \InvalidArgumentException(
101
+                    sprintf('The plugin %s must be an instance of %s', get_class($plugin), Plugin::class)
102
+                );
103
+            }
104
+        }
105
+
106
+        if ($update instanceof Update) {
107
+            $this->spreadUpdateWith($update, $plugins);
108
+        }
109
+    }
110
+
111
+    /**
112
+     * Match the message to the plugins
113
+     *
114
+     * @param ?Update $update The update to match
115
+     * @return void
116
+     */
117
+    public function loadPlugins(Update $update = null): void
118
+    {
119
+        $update = $update ?? ($this->update ?? Telegram::getUpdate());
120
+        $this->loadPluginsWith($this->plugins, $update);
121
+    }
122
+
123
+    /**
124
+     * Load the environment's
125
+     *
126
+     * @param string $path
127
+     * @retrun void
128
+     */
129
+    public function loadFileOfEnv(string $path): void
130
+    {
131
+        DotEnv::load($path);
132
+    }
133
+
134
+    /**
135
+     * Update the configuration
136
+     *
137
+     * @param array $configuration
138
+     * @return void
139
+     */
140
+    public function updateConfiguration(array $configuration): void
141
+    {
142
+        $this->config = array_merge($this->config, $configuration);
143
+    }
144
+
145
+    /**
146
+     * Resolve the request.
147
+     *
148
+     * @param ?Update $update The custom to work with
149
+     * @param array $config The configuration of the receiver
150
+     *
151
+     * @retrun void
152
+     */
153
+    public function resolve(Update $update = null, array $config = []): void
154
+    {
155
+        $method = '__process';
156
+        if (!method_exists($this, $method)) {
157
+            throw new \RuntimeException(sprintf('The method %s does not exist', $method));
158
+        }
159
+
160
+        if (is_array($config)) $this->updateConfiguration($config);
161
+
162
+        if (!empty($update)) $this->update = $update;
163
+        else $this->update = Telegram::getUpdate() !== false ? Telegram::getUpdate() : null;
164
+
165
+        if (empty($this->update)) {
166
+            TelegramLog::error(
167
+                'The update is empty, the request is not processed'
168
+            );
169
+            return;
170
+        }
171
+
172
+        try {
173
+
174
+            Common::arrest($this, $method, $this->update);
175
+
176
+        } catch (\RuntimeException $exception) {
177
+
178
+            $e = $exception->getPrevious();
179
+            TelegramLog::error(($message = sprintf(
180
+                '%s(%d): %s\n%s', $e->getFile(), $e->getLine(), $e->getMessage(), $e->getTraceAsString()
181
+            )));
182
+
183
+            if (defined('TG_ADMIN_ID') && TG_ADMIN_ID && defined('DEBUG_MODE') && DEBUG_MODE) {
184
+                file_put_contents(
185
+                    ($file = getcwd() . '/' . uniqid('error_') . '.log'),
186
+                    $message . PHP_EOL . PHP_EOL . $update->getRawData(false)
187
+                );
188
+                Request::sendMessage([
189
+                    'chat_id' => TG_ADMIN_ID,
190
+                    'text' => $message,
191
+                ]);
192
+                Request::sendDocument([
193
+                    'chat_id' => TG_ADMIN_ID,
194
+                    'document' => $file,
195
+                ]);
196
+                unlink($file);
197
+            }
198
+        }
199
+    }
200
+
201
+    /**
202
+     * This function will get update and spread it to the plugins
203
+     *
204
+     * @param Update $update
205
+     * @param array<Plugin> $plugins
206
+     * @return void
207
+     */
208
+    private function spreadUpdateWith(Update $update, array $plugins): void
209
+    {
210
+        $this->isActive = true;
211
+
212
+        foreach ($plugins as $plugin) {
213
+            /** @var Plugin $plugin */
214
+            (new $plugin())->__execute($this, $update);
215
+            if ($this->isActive === false) break;
216
+        }
217
+
218
+        $this->isActive = false;
219
+    }
220
+
221
+    /**
222
+     * Kill the speeding process
223
+     *
224
+     * @return void
225
+     */
226
+    public function kill(): void
227
+    {
228
+        $this->isActive = false;
229
+    }
230
+
231
+    /**
232
+     * Use this method on the webhook class to get the updates
233
+     *
234
+     * @param Update $update
235
+     * @return void
236
+     */
237
+    abstract public function __process(Update $update): void;
238
+
239
+    /**
240
+     * put CrossData into the plugins
241
+     *
242
+     * @param string $key
243
+     * @param mixed $value
244
+     * @return void
245
+     */
246
+    public function putCrossData(string $key, mixed $value): void
247
+    {
248
+        CrossData::put($key, $value);
249
+    }
250
+
251
+    /**
252
+     * get CrossData from the plugins
253
+     *
254
+     * @param string $key
255
+     * @return string|array|bool|null
256
+     */
257
+    public function getCrossData(string $key): string|array|bool|null
258
+    {
259
+        return CrossData::get($key);
260
+    }
261 261
 
262 262
 }
263 263
\ No newline at end of file
Please login to merge, or discard this patch.
src/lib/Entities/InlineKeyboardButton.php 1 patch
Indentation   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -35,49 +35,49 @@
 block discarded – undo
35 35
 class InlineKeyboardButton extends KeyboardButton
36 36
 {
37 37
 
38
-	/**
39
-	 * Creates instance of InlineKeyboardButton
40
-	 *
41
-	 * @param string $string
42
-	 * @return InlineKeyboardButton
43
-	 */
44
-	public static function make(string $string): InlineKeyboardButton
45
-	{
46
-		return new self($string);
47
-	}
38
+    /**
39
+     * Creates instance of InlineKeyboardButton
40
+     *
41
+     * @param string $string
42
+     * @return InlineKeyboardButton
43
+     */
44
+    public static function make(string $string): InlineKeyboardButton
45
+    {
46
+        return new self($string);
47
+    }
48 48
 
49
-	/**
50
-	 * @param string $data
51
-	 * @return $this
52
-	 */
53
-	public function CallbackData(string $data): InlineKeyboardButton
54
-	{
55
-		$this->raw_data['callback_data'] = $data;
49
+    /**
50
+     * @param string $data
51
+     * @return $this
52
+     */
53
+    public function CallbackData(string $data): InlineKeyboardButton
54
+    {
55
+        $this->raw_data['callback_data'] = $data;
56 56
 
57
-		return $this;
58
-	}
57
+        return $this;
58
+    }
59 59
 
60
-	/**
61
-	 * @param string $data
62
-	 * @return $this
63
-	 */
64
-	public function Url(string $data): InlineKeyboardButton
65
-	{
66
-		$this->raw_data['url'] = $data;
60
+    /**
61
+     * @param string $data
62
+     * @return $this
63
+     */
64
+    public function Url(string $data): InlineKeyboardButton
65
+    {
66
+        $this->raw_data['url'] = $data;
67 67
 
68
-		return $this;
69
-	}
68
+        return $this;
69
+    }
70 70
 
71
-	/**
72
-	 * @param string $url
73
-	 * @return $this
74
-	 */
75
-	public function WebApp(string $url): KeyboardButton
76
-	{
77
-		$this->raw_data['web_app'] = new WebAppInfo(['url' => $url]);
71
+    /**
72
+     * @param string $url
73
+     * @return $this
74
+     */
75
+    public function WebApp(string $url): KeyboardButton
76
+    {
77
+        $this->raw_data['web_app'] = new WebAppInfo(['url' => $url]);
78 78
 
79
-		return $this;
80
-	}
79
+        return $this;
80
+    }
81 81
 
82 82
     /**
83 83
      * Check if the passed data array could be an InlineKeyboardButton.
Please login to merge, or discard this patch.
src/lib/Util/CrossData.php 1 patch
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -12,37 +12,37 @@
 block discarded – undo
12 12
 class CrossData
13 13
 {
14 14
 
15
-	/**
16
-	 * get CrossData
17
-	 *
18
-	 * @param string $key
19
-	 * @return string|array|bool|null
20
-	 */
21
-	public static function get(string $key): string|array|bool|null
22
-	{
23
-		$data = json_decode(getenv('TG_CROSS_DATA'), true);
24
-		$block = 'TG_CROSS_DATA' . $key;
15
+    /**
16
+     * get CrossData
17
+     *
18
+     * @param string $key
19
+     * @return string|array|bool|null
20
+     */
21
+    public static function get(string $key): string|array|bool|null
22
+    {
23
+        $data = json_decode(getenv('TG_CROSS_DATA'), true);
24
+        $block = 'TG_CROSS_DATA' . $key;
25 25
 
26
-		if (!isset($data[$key])) {
27
-			return null;
28
-		}
26
+        if (!isset($data[$key])) {
27
+            return null;
28
+        }
29 29
 
30
-		return getenv($data[$block]);
31
-	}
30
+        return getenv($data[$block]);
31
+    }
32 32
 
33
-	/**
34
-	 * put CrossData
35
-	 *
36
-	 * @param string $key
37
-	 * @param mixed $value
38
-	 * @return void
39
-	 */
40
-	public static function put(string $key, mixed $value): void
41
-	{
42
-		$data = json_decode(getenv('TG_CROSS_DATA'), true);
43
-		$data[$key] = 'TG_CROSS_DATA_' . $key;
44
-		putenv($data[$key] . '=' . $value);
45
-		putenv(json_encode($data));
46
-	}
33
+    /**
34
+     * put CrossData
35
+     *
36
+     * @param string $key
37
+     * @param mixed $value
38
+     * @return void
39
+     */
40
+    public static function put(string $key, mixed $value): void
41
+    {
42
+        $data = json_decode(getenv('TG_CROSS_DATA'), true);
43
+        $data[$key] = 'TG_CROSS_DATA_' . $key;
44
+        putenv($data[$key] . '=' . $value);
45
+        putenv(json_encode($data));
46
+    }
47 47
 
48 48
 }
49 49
\ No newline at end of file
Please login to merge, or discard this patch.
src/lib/Plugin.php 1 patch
Indentation   +124 added lines, -124 removed lines patch added patch discarded remove patch
@@ -15,129 +15,129 @@
 block discarded – undo
15 15
 class Plugin
16 16
 {
17 17
 
18
-	/**
19
-	 * The Update types
20
-	 *
21
-	 * @var array
22
-	 */
23
-	protected array $update_types = [
24
-		'Message',
25
-		'EditedMessage',
26
-		'ChannelPost',
27
-		'EditedChannelPost',
28
-		'InlineQuery',
29
-		'ChosenInlineResult',
30
-		'CallbackQuery',
31
-		'ShippingQuery',
32
-		'PreCheckoutQuery',
33
-	];
34
-
35
-	/**
36
-	 * @var WebhookHandler
37
-	 */
38
-	protected WebhookHandler $hook;
39
-
40
-	/**
41
-	 * @var \Generator
42
-	 */
43
-	protected \Generator $returns;
44
-
45
-	/**
46
-	 * @var bool
47
-	 */
48
-	protected bool $kill_on_yield = false;
49
-
50
-	/**
51
-	 * Check for the exit of the plugin.
52
-	 *
53
-	 * @param \Generator $return
54
-	 * @return void
55
-	 */
56
-	public function __checkExit(\Generator $return): void
57
-	{
58
-		if ($return->valid()) {
59
-			if ($return->current() !== null && $this->kill_on_yield === true) {
60
-				$this->kill();
61
-			}
62
-		}
63
-
64
-		if ($return->valid()) {
65
-			$return->next();
66
-			$this->__checkExit($return);
67
-		}
68
-	}
69
-
70
-	/**
71
-	 * Identify the update type. e.g. Message, EditedMessage, etc.
72
-	 *
73
-	 * @param Update $update
74
-	 * @return string|null
75
-	 */
76
-	public function __identify(Update $update): ?string
77
-	{
78
-		$type = $update->getUpdateType();
79
-
80
-		if ($type === null) {
81
-			return null;
82
-		}
83
-
84
-		return str_replace('_', '', ucwords($type, '_'));
85
-	}
86
-
87
-	/**
88
-	 * Execute the plugin.
89
-	 *
90
-	 * @param WebhookHandler $receiver
91
-	 * @param Update $update
92
-	 * @return void
93
-	 */
94
-	public function __execute(WebhookHandler $receiver, Update $update): void
95
-	{
96
-		$this->hook = $receiver;
97
-
98
-		if (method_exists($this, 'onReceivedUpdate')) {
99
-			$return = $this->onReceivedUpdate($update);
100
-			$this->__checkExit($return);
101
-		}
102
-
103
-		$type = $this->__identify($update);
104
-		if (method_exists($this, ($method = 'on' . $type)) && $type !== null) {
105
-			$return = $this->$method($update);
106
-			$this->__checkExit($return);
107
-		}
108
-	}
109
-
110
-	/**
111
-	 * Kill the plugin.
112
-	 *
113
-	 * @return void
114
-	 */
115
-	public function kill(): void
116
-	{
117
-		$this->hook->kill();
118
-	}
119
-
120
-	/**
121
-	 * put CrossData into the plugins
122
-	 *
123
-	 * @param string $key
124
-	 * @param mixed $value
125
-	 * @return void
126
-	 */
127
-	public function putCrossData(string $key, mixed $value): void
128
-	{
129
-		CrossData::put($key, $value);
130
-	}
131
-
132
-	/**
133
-	 * get CrossData from the plugins
134
-	 *
135
-	 * @param string $key
136
-	 * @return string|array|bool|null
137
-	 */
138
-	public function getCrossData(string $key): string|array|bool|null
139
-	{
140
-		return CrossData::get($key);
141
-	}
18
+    /**
19
+     * The Update types
20
+     *
21
+     * @var array
22
+     */
23
+    protected array $update_types = [
24
+        'Message',
25
+        'EditedMessage',
26
+        'ChannelPost',
27
+        'EditedChannelPost',
28
+        'InlineQuery',
29
+        'ChosenInlineResult',
30
+        'CallbackQuery',
31
+        'ShippingQuery',
32
+        'PreCheckoutQuery',
33
+    ];
34
+
35
+    /**
36
+     * @var WebhookHandler
37
+     */
38
+    protected WebhookHandler $hook;
39
+
40
+    /**
41
+     * @var \Generator
42
+     */
43
+    protected \Generator $returns;
44
+
45
+    /**
46
+     * @var bool
47
+     */
48
+    protected bool $kill_on_yield = false;
49
+
50
+    /**
51
+     * Check for the exit of the plugin.
52
+     *
53
+     * @param \Generator $return
54
+     * @return void
55
+     */
56
+    public function __checkExit(\Generator $return): void
57
+    {
58
+        if ($return->valid()) {
59
+            if ($return->current() !== null && $this->kill_on_yield === true) {
60
+                $this->kill();
61
+            }
62
+        }
63
+
64
+        if ($return->valid()) {
65
+            $return->next();
66
+            $this->__checkExit($return);
67
+        }
68
+    }
69
+
70
+    /**
71
+     * Identify the update type. e.g. Message, EditedMessage, etc.
72
+     *
73
+     * @param Update $update
74
+     * @return string|null
75
+     */
76
+    public function __identify(Update $update): ?string
77
+    {
78
+        $type = $update->getUpdateType();
79
+
80
+        if ($type === null) {
81
+            return null;
82
+        }
83
+
84
+        return str_replace('_', '', ucwords($type, '_'));
85
+    }
86
+
87
+    /**
88
+     * Execute the plugin.
89
+     *
90
+     * @param WebhookHandler $receiver
91
+     * @param Update $update
92
+     * @return void
93
+     */
94
+    public function __execute(WebhookHandler $receiver, Update $update): void
95
+    {
96
+        $this->hook = $receiver;
97
+
98
+        if (method_exists($this, 'onReceivedUpdate')) {
99
+            $return = $this->onReceivedUpdate($update);
100
+            $this->__checkExit($return);
101
+        }
102
+
103
+        $type = $this->__identify($update);
104
+        if (method_exists($this, ($method = 'on' . $type)) && $type !== null) {
105
+            $return = $this->$method($update);
106
+            $this->__checkExit($return);
107
+        }
108
+    }
109
+
110
+    /**
111
+     * Kill the plugin.
112
+     *
113
+     * @return void
114
+     */
115
+    public function kill(): void
116
+    {
117
+        $this->hook->kill();
118
+    }
119
+
120
+    /**
121
+     * put CrossData into the plugins
122
+     *
123
+     * @param string $key
124
+     * @param mixed $value
125
+     * @return void
126
+     */
127
+    public function putCrossData(string $key, mixed $value): void
128
+    {
129
+        CrossData::put($key, $value);
130
+    }
131
+
132
+    /**
133
+     * get CrossData from the plugins
134
+     *
135
+     * @param string $key
136
+     * @return string|array|bool|null
137
+     */
138
+    public function getCrossData(string $key): string|array|bool|null
139
+    {
140
+        return CrossData::get($key);
141
+    }
142 142
 
143 143
 }
144 144
\ No newline at end of file
Please login to merge, or discard this patch.