Passed
Push — master ( 1b4865...c6e62a )
by Edward
02:24
created

PathEncoder   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 21
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 4
eloc 7
c 1
b 0
f 1
dl 0
loc 21
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A encodePathElement() 0 13 3
A encodePath() 0 3 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Remorhaz\JSON\Path\Processor;
5
6
use function array_map;
7
use function implode;
8
use function is_int;
9
use function is_string;
10
use Remorhaz\JSON\Data\Path\PathInterface;
11
use function str_replace;
12
13
final class PathEncoder implements PathEncoderInterface
14
{
15
16
    public function encodePath(PathInterface $path): string
17
    {
18
        return '$' . implode('', array_map([$this, 'encodePathElement'], $path->getElements()));
19
    }
20
21
    private function encodePathElement($pathElement): string
22
    {
23
        if (is_int($pathElement)) {
24
            return "[{$pathElement}]";
25
        }
26
27
        if (is_string($pathElement)) {
28
            $escapedElement = str_replace(['\\', '\''], ['\\\\', '\\\''], $pathElement);
29
30
            return "['{$escapedElement}']";
31
        }
32
33
        throw new Exception\InvalidPathElementException($pathElement);
34
    }
35
}
36