Completed
Push — master ( f80ae4...a68096 )
by Derek
02:04
created

Query::isValid()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
namespace Subreality\Dilmun\Anshar\Http\UriParts;
3
4
/**
5
 * Class Query
6
 * @package Subreality\Dilmun\Anshar\Http\UriParts
7
 */
8
class Query
9
{
10
    private $unreserved_pattern  = '\w\-\.~';
11
    private $pct_encoded_pattern = '%[A-Fa-f0-9]{2}';
12
    private $sub_delims_pattern  = '\!\$&\'\(\)\*\+,;\=';
13
    private $pchar_pattern       = '\:@';
14
15
    private static $valid_pattern;
16
17
    private $query = "";
18
19
    /**
20
     * Query constructor. Accepts a string representing a URI query. Construction will throw an exception if the
21
     * query is either not a string or does not conform to the RFC3986 URI query specification.
22
     *
23
     * query       = *( pchar / "/" / "?" )
24
     * pchar       = unreserved / pct-encoded / sub-delims / ":" / "@"
25
     * unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"
26
     * pct-encoded = "%" HEXDIG HEXDIG
27
     * sub-delims  = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
28
     *
29
     * @see https://tools.ietf.org/html/rfc3986#appendix-A
30
     *
31
     * @throws \InvalidArgumentException
32
     *
33
     * @param string $query     A string representing a URI query
34
     */
35 11
    public function __construct($query)
36
    {
37 11
        $this->compileValidPattern();
38
39 11
        if (!is_string($query)) {
40 6
            throw new \InvalidArgumentException("Query must be a string");
41 5
        } elseif (!self::isValid($query)) {
42 3
            throw new \InvalidArgumentException("Query must conform to RFC3986 specification");
43
        }
44
45 2
        $this->query = $query;
46 2
    }
47
48
    /**
49
     * Returns a string representation of the query
50
     *
51
     * @return string   A string representation of the query
52
     */
53 3
    public function __toString()
54
    {
55 3
        return $this->query;
56
    }
57
58 15
    public static function isValid($query)
59
    {
60 15
        return (bool) preg_match(self::$valid_pattern, $query);
61
    }
62
63
    /**
64
     * Compiles a regexp pattern based on predefined patterns that define allowed characters for a query. Note that the
65
     * pipe indicates that a query can either contain all defined characters or contain percent encoded characters.
66
     */
67 11
    private function compileValidPattern()
68
    {
69 11
        self::$valid_pattern = '/^([\/\?' .
70 11
            $this->unreserved_pattern .
71 11
            $this->sub_delims_pattern .
72 11
            $this->pchar_pattern .
73 11
            ']|' .
74 11
            $this->pct_encoded_pattern .
75 11
            ')*$/';
76 11
    }
77
}
78