Passed
Branch feature/first-release (f6e752)
by Andrea Marco
02:33
created

AbstractHandler::pointer()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 9
ccs 0
cts 5
cp 0
rs 10
cc 2
nc 2
nop 0
crap 6
1
<?php
2
3
namespace Cerbero\LazyJson\Handlers;
4
5
use Traversable;
6
7
/**
8
 * The abstract handler.
9
 *
10
 */
11
abstract class AbstractHandler
12
{
13
    /**
14
     * The JSON source.
15
     *
16
     * @var mixed
17
     */
18
    protected $source;
19
20
    /**
21
     * The dot-noted path.
22
     *
23
     * @var string
24
     */
25
    protected $path;
26
27
    /**
28
     * Instantiate the class.
29
     *
30
     * @param mixed $source
31
     * @param string $path
32
     */
33
    public function __construct(&$source, string $path)
34
    {
35
        $this->source = &$source;
36
        $this->path = $path;
37
    }
38
39
    /**
40
     * Determine whether the handler should handle the source
41
     *
42
     * @return bool
43
     */
44
    abstract protected function shouldHandleSource(): bool;
45
46
    /**
47
     * Handle the source
48
     *
49
     * @return Traversable|null
50
     */
51
    abstract protected function handleSource(): ?Traversable;
52
53
    /**
54
     * Instantiate the class
55
     *
56
     * @param mixed $source
57
     * @param string $path
58
     * @return self
59
     */
60
    public static function of(&$source, string $path): self
61
    {
62
        return new static($source, $path);
63
    }
64
65
    /**
66
     * Attempts to retrieve a traversable JSON from the source
67
     *
68
     * @return Traversable|null
69
     */
70
    public function handle(): ?Traversable
71
    {
72
        return $this->shouldHandleSource() ? $this->handleSource() : null;
73
    }
74
75
    /**
76
     * Retrieve the JSON pointer of the dot-noted path
77
     *
78
     * @param string $path
79
     * @return string
80
     */
81
    protected function pointer(): string
82
    {
83
        $path = trim($this->path);
84
85
        if (empty($path)) {
86
            return '';
87
        }
88
89
        return '/' . str_replace(['~', '/', '.', '*'], ['~0', '~1', '/', '-'], $path);
90
    }
91
}
92