Passed
Push — master ( 8e3f03...61985e )
by Sebastian
02:32
created

ConvertHelper_QueryParser   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 4
eloc 13
c 2
b 0
f 0
dl 0
loc 44
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A parse() 0 27 3
1
<?php
2
/**
3
 * File containing the {@see AppUtils\ConvertHelper_QueryParser} class.
4
 *
5
 * @package Application Utils
6
 * @subpackage ConvertHelper
7
 * @see AppUtils\ConvertHelper_QueryParser
8
 */
9
10
declare(strict_types=1);
11
12
namespace AppUtils;
13
14
/**
15
 * Query parser that works as a drop-in for the native
16
 * PHP function parse_str, and which overcomes this function's
17
 * limitations.
18
 *
19
 * @package Application Utils
20
 * @subpackage ConvertHelper
21
 * @see https://www.php.net/manual/en/function.parse-str.php
22
 */
23
class ConvertHelper_QueryParser
24
{
25
    public function __construct()
26
    {
27
        
28
    }
29
    
30
   /**
31
    * We parse the query string ourselves, because the PHP implementation
32
    * of parse_str has limitations that do not apply to query strings. This
33
    * is due to the fact that parse_str has to create PHP-compatible variable
34
    * names from the parameters. URL parameters simply allow way more things
35
    * than PHP variable names.
36
    * 
37
    * @param string $queryString
38
    * @return array
39
    */
40
    public function parse(string $queryString) : array
41
    {
42
        // allow HTML entities notation
43
        $queryString = str_replace('&amp;', '&', $queryString);
44
        
45
        $parts = explode('&', $queryString);
46
        
47
        $result = array();
48
        
49
        foreach($parts as $part)
50
        {
51
            $tokens = explode('=', $part);
52
            
53
            $name = urldecode(array_shift($tokens));
54
            $value = urldecode(implode('=', $tokens));
55
56
            $trimmed = trim($name);
57
            
58
            if(empty($trimmed))
59
            {
60
                continue;
61
            }
62
            
63
            $result[$name] = $value;
64
        }
65
        
66
        return $result;
67
    }
68
}
69