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

Parser   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 94
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%
Metric Value
dl 0
loc 94
ccs 31
cts 31
cp 1
rs 10
wmc 10
lcom 1
cbo 1

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A get() 0 4 1
A parse() 0 8 1
A explode() 0 6 1
A urlDecode() 0 6 1
A untilde() 0 10 1
A validate() 0 14 4
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