Passed
Push — master ( 6a6913...9c7b82 )
by Shahrad
02:17
created

Common::setDebugMode()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 5
c 0
b 0
f 0
nc 6
nop 1
dl 0
loc 7
rs 10
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);
0 ignored issues
show
Bug Best Practice introduced by
The expression return preg_match('/%[0-9A-F]{2}/i', $string) returns the type integer which is incompatible with the type-hinted return boolean.
Loading history...
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
}