Test Failed
Push — master ( cc6cb5...f69508 )
by Shahrad
10:37
created

Toolkit   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 18
dl 0
loc 60
c 1
b 0
f 0
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isUrlEncode() 0 7 2
A urlDecode() 0 19 4
A isJson() 0 9 2
1
<?php
2
3
namespace TelegramBot\Util;
4
5
/**
6
 * Toolkit class
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 Toolkit
13
{
14
15
    /**
16
     * Convert url encoded string to array
17
     *
18
     * @param string $string
19
     * @return array
20
     */
21
    public static function urlDecode(string $string): array
22
    {
23
        $raw_data = explode('&', urldecode($string));
24
        $data = [];
25
26
        foreach ($raw_data as $row) {
27
            [$key, $value] = explode('=', $row);
28
29
            if (self::isUrlEncode($value)) {
30
                $value = urldecode($value);
31
                if (self::isJson($value)) {
32
                    $value = json_decode($value, true);
33
                }
34
            }
35
36
            $data[$key] = $value;
37
        }
38
39
        return $data;
40
    }
41
42
    /**
43
     * Check string is a url encoded string or not
44
     *
45
     * @param ?string $string
46
     * @return bool
47
     */
48
    public static function isUrlEncode(?string $string): bool
49
    {
50
        if (!is_string($string)) {
51
            return false;
52
        }
53
54
        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...
55
    }
56
57
    /**
58
     * Validate the given string is JSON or not
59
     *
60
     * @param ?string $string
61
     * @return bool
62
     */
63
    public static function isJson(?string $string): bool
64
    {
65
        if (!is_string($string)) {
66
            return false;
67
        }
68
69
        json_decode($string);
70
71
        return json_last_error() === JSON_ERROR_NONE;
72
    }
73
74
}