Passed
Push — master ( 95373b...dd07b4 )
by Nate
43s
created

JsonPath::getPath()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 4
nop 0
dl 0
loc 19
ccs 10
cts 10
cp 1
crap 4
rs 9.9666
c 0
b 0
f 0
1
<?php
2
/*
3
 * Copyright (c) Nate Brunette.
4
 * Distributed under the MIT License (http://opensource.org/licenses/MIT)
5
 */
6
7
declare(strict_types=1);
8
9
namespace Tebru\Gson\Internal;
10
11
/**
12
 * Trait JsonPath
13
 *
14
 * Used during reading/writing to keep track of the current path
15
 *
16
 * @author Nate Brunette <[email protected]>
17
 */
18
trait JsonPath
19
{
20
    /**
21
     * An array of path names that correspond to the current stack
22
     *
23
     * @var array
24
     */
25
    protected $pathNames = [];
26
27
    /**
28
     * An array of path indices that correspond to the current stack. This array could contain invalid
29
     * values at indexes outside the current stack. It could also contain incorrect values at indexes
30
     * where a path name is used. Data should only be fetched by referencing the $pathIndex
31
     *
32
     * @var int[]
33
     */
34
    protected $pathIndices = [-1];
35
36
    /**
37
     * The current path index corresponding to the pathIndices array
38
     *
39
     * @var int
40
     */
41
    protected $pathIndex = 0;
42
43
    /**
44
     * Get the current read path in json xpath format
45
     *
46
     * @return string
47
     */
48 82
    public function getPath(): string
49
    {
50 82
        $result = ['$'];
51
52 82
        for ($index = 1; $index <= $this->pathIndex; $index++) {
53 62
            if (!empty($this->pathNames[$index])) {
54 26
                $result[] .= '.'.$this->pathNames[$index];
55 26
                continue;
56
            }
57
58
            // skip initial value
59 48
            if ($this->pathIndices[$index] === -1) {
60 30
                continue;
61
            }
62
63 22
            $result[] .= '['.$this->pathIndices[$index].']';
64
        }
65
66 82
        return implode($result);
67
    }
68
}
69