JsonValueReplace::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
cc 1
nc 1
nop 3
crap 1
1
<?php
2
3
namespace Swaggest\JsonDiff;
4
5
6
class JsonValueReplace
7
{
8
    private $search;
9
    private $replace;
10
    private $pathFilterRegex;
11
    private $path = '';
12
    private $pathItems = array();
13
14
    public $affectedPaths = array();
15
16
    /**
17
     * JsonReplace constructor.
18
     * @param mixed $search
19
     * @param mixed $replace
20
     * @param null|string $pathFilter Regular expression to check path
21
     */
22 3
    public function __construct($search, $replace, $pathFilter = null)
23
    {
24 3
        $this->search = $search;
25 3
        $this->replace = $replace;
26 3
        $this->pathFilterRegex = $pathFilter;
27 3
    }
28
29
    /**
30
     * Recursively replaces all nodes equal to `search` value with `replace` value.
31
     * @param mixed $data
32
     * @return mixed
33
     * @throws Exception
34
     */
35 3
    public function process($data)
36
    {
37 3
        $check = true;
38 3
        if ($this->pathFilterRegex && !preg_match($this->pathFilterRegex, $this->path)) {
39 1
            $check = false;
40
        }
41
42 3
        if (!is_array($data) && !is_object($data)) {
43 3
            if ($check && $data === $this->search) {
44 1
                $this->affectedPaths[] = $this->path;
45 1
                return $this->replace;
46
            } else {
47 3
                return $data;
48
            }
49
        }
50
51 3
        /** @var string[] $originalKeys */
52
        $originalKeys = $data instanceof \stdClass ? get_object_vars($data) : $data;
53 3
54 3
        if ($check) {
55 3
            $diff = new JsonDiff($data, $this->search, JsonDiff::STOP_ON_DIFF);
56 2
            if ($diff->getDiffCnt() === 0) {
57 2
                $this->affectedPaths[] = $this->path;
58
                return $this->replace;
59
            }
60
        }
61 3
62
        $result = array();
63 3
64 3
        foreach ($originalKeys as $key => $originalValue) {
65 3
            $path = $this->path;
66 3
            $pathItems = $this->pathItems;
67 3
            $actualKey = $key;
68 3
            $this->path .= '/' . JsonPointer::escapeSegment($actualKey);
69
            $this->pathItems[] = $actualKey;
70 3
71
            $result[$key] = $this->process($originalValue);
72 3
73 3
            $this->path = $path;
74
            $this->pathItems = $pathItems;
75
        }
76 3
77
        return $data instanceof \stdClass ? (object)$result : $result;
78
    }
79
}