Passed
Push — master ( 3ea708...b1fd4c )
by Viacheslav
01:58
created

JsonValueReplace::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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