|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace TelegramBot\Util; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* Class Common |
|
7
|
|
|
* |
|
8
|
|
|
* @link https://github.com/telegram-bot-php/core |
|
9
|
|
|
* @author Shahrad Elahi (https://github.com/shahradelahi) |
|
10
|
|
|
* @license https://github.com/telegram-bot-php/core/blob/master/LICENSE (MIT License) |
|
11
|
|
|
*/ |
|
12
|
|
|
class Common |
|
13
|
|
|
{ |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Validate the given string is JSON or not |
|
17
|
|
|
* |
|
18
|
|
|
* @param ?string $string |
|
19
|
|
|
* @return bool |
|
20
|
|
|
*/ |
|
21
|
|
|
public static function isJson(?string $string): bool |
|
22
|
|
|
{ |
|
23
|
|
|
if (!is_string($string)) return false; |
|
24
|
|
|
json_decode($string); |
|
25
|
|
|
return json_last_error() === JSON_ERROR_NONE; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* Arrest with exception |
|
30
|
|
|
* |
|
31
|
|
|
* @param mixed $class The class |
|
32
|
|
|
* @param string $callback The method |
|
33
|
|
|
* @param mixed ...$args The arguments to pass to the callback |
|
34
|
|
|
* @return mixed |
|
35
|
|
|
*/ |
|
36
|
|
|
public static function arrest(mixed $class, string $callback, ...$args): mixed |
|
37
|
|
|
{ |
|
38
|
|
|
try { |
|
39
|
|
|
return call_user_func_array([$class, $callback], $args); |
|
40
|
|
|
} catch (\Throwable|\TypeError|\Exception $e) { |
|
41
|
|
|
if (defined('DEBUG_MODE') && DEBUG_MODE) { |
|
42
|
|
|
echo '<b>TelegramError:</b> ' . $e->getMessage() . PHP_EOL; |
|
43
|
|
|
} |
|
44
|
|
|
throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* Check string is a url encoded string or not |
|
50
|
|
|
* |
|
51
|
|
|
* @param string $string |
|
52
|
|
|
* @return bool |
|
53
|
|
|
*/ |
|
54
|
|
|
public static function isUrlEncode(string $string): bool |
|
55
|
|
|
{ |
|
56
|
|
|
return preg_match('/%[0-9A-F]{2}/i', $string); |
|
|
|
|
|
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* Convert url encoded string to array |
|
61
|
|
|
* |
|
62
|
|
|
* @param string $string |
|
63
|
|
|
* @return array |
|
64
|
|
|
*/ |
|
65
|
|
|
public static function urlDecode(string $string): array |
|
66
|
|
|
{ |
|
67
|
|
|
$raw_data = explode('&', urldecode($string)); |
|
68
|
|
|
$data = []; |
|
69
|
|
|
|
|
70
|
|
|
foreach ($raw_data as $row) { |
|
71
|
|
|
[$key, $value] = explode('=', $row); |
|
72
|
|
|
|
|
73
|
|
|
if (self::isUrlEncode($value)) { |
|
74
|
|
|
$value = urldecode($value); |
|
75
|
|
|
if (self::isJson($value)) { |
|
76
|
|
|
$value = json_decode($value, true); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
$data[$key] = $value; |
|
81
|
|
|
} |
|
82
|
|
|
|
|
83
|
|
|
return $data; |
|
84
|
|
|
} |
|
85
|
|
|
|
|
86
|
|
|
} |