Completed
Push — master ( 5927eb...1e13db )
by
unknown
04:04
created

Parser::parse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1
Metric Value
cc 1
eloc 6
nc 1
nop 1
dl 0
loc 8
ccs 6
cts 6
cp 1
crap 1
rs 9.4285
1
<?php
2
3
namespace League\JsonGuard\Pointer;
4
5
/**
6
 * Parses a JSON Pointer as defined in the specification.
7
 * @see https://tools.ietf.org/html/rfc6901#section-4
8
 */
9
class Parser
10
{
11
    /**
12
     * @var array
13
     */
14
    private $pointer;
15
16
    /**
17
     * @param $pointer
18
     */
19 40
    public function __construct($pointer)
20
    {
21 40
        $this->validate($pointer);
22 36
        $this->pointer = $this->parse($pointer);
23 36
    }
24
25
    /**
26
     * @return array
27
     */
28 36
    public function get()
29
    {
30 36
        return $this->pointer;
31
    }
32
33
    /**
34
     * @param string $pointer
35
     *
36
     * @return array
37
     */
38 36
    private function parse($pointer)
39
    {
40 36
        return $this
41 36
            ->explode($pointer)
42 36
            ->urlDecode()
43 36
            ->untilde()
44 36
            ->get();
45
    }
46
47
    /**
48
     * @param string $pointer
49
     *
50
     * @return $this
51
     */
52 36
    private function explode($pointer)
53
    {
54 36
        $this->pointer = array_slice(explode('/', $pointer), 1);
55
56 36
        return $this;
57
    }
58
59
    /**
60
     * @return $this
61
     */
62 36
    private function urlDecode()
63
    {
64 36
        $this->pointer = array_map('urldecode', $this->pointer);
65
66 36
        return $this;
67
    }
68
69
    /**
70
     * @return $this
71
     */
72
    private function untilde()
73
    {
74 36
        $this->pointer = array_map(function ($segment) {
75 36
            $segment = str_replace('~1', '/', $segment);
76
77 36
            return str_replace('~0', '~', $segment);
78 36
        }, $this->pointer);
79
80 36
        return $this;
81
    }
82
83
    /**
84
     * @param string $pointer
85
     *
86
     * @throws InvalidPointerException
87
     */
88 40
    private function validate($pointer)
89
    {
90 40
        if ($pointer === '') {
91 18
            return;
92
        }
93
94 40
        if (!is_string($pointer)) {
95 2
            throw InvalidPointerException::invalidType(gettype($pointer));
96
        }
97
98 38
        if (strpos($pointer, '/') !== 0) {
99 2
            throw InvalidPointerException::invalidFirstCharacter(substr($pointer, 0, 1));
100
        }
101 36
    }
102
}
103