Passed
Push — master ( b5fef0...47a2b4 )
by Shahrad
02:38
created

Common   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Importance

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

3 Methods

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