Skip to content

Commit 67f2acf

Browse files
committed
JsonValueReplace
1 parent 4e76cd7 commit 67f2acf

File tree

2 files changed

+60
-5
lines changed

2 files changed

+60
-5
lines changed

Diff for: src/JsonValueReplace.php

+23-5
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,23 @@ class JsonValueReplace
77
{
88
private $search;
99
private $replace;
10+
private $pathFilterRegex;
1011
private $path = '';
1112
private $pathItems = array();
1213

14+
public $affectedPaths = array();
15+
1316
/**
1417
* JsonReplace constructor.
1518
* @param mixed $search
1619
* @param mixed $replace
20+
* @param null|string $pathFilter Regular expression to check path
1721
*/
18-
public function __construct($search, $replace)
22+
public function __construct($search, $replace, $pathFilter = null)
1923
{
2024
$this->search = $search;
2125
$this->replace = $replace;
26+
$this->pathFilterRegex = $pathFilter;
2227
}
2328

2429
/**
@@ -28,15 +33,28 @@ public function __construct($search, $replace)
2833
*/
2934
public function process($data)
3035
{
36+
$check = true;
37+
if ($this->pathFilterRegex && !preg_match($this->pathFilterRegex, $this->path)) {
38+
$check = false;
39+
}
40+
3141
if (!is_array($data) && !is_object($data)) {
32-
return $data === $this->search ? $this->replace : $data;
42+
if ($check && $data === $this->search) {
43+
$this->affectedPaths[] = $this->path;
44+
return $this->replace;
45+
} else {
46+
return $data;
47+
}
3348
}
3449

3550
$originalKeys = $data instanceof \stdClass ? get_object_vars($data) : $data;
3651

37-
$diff = new JsonDiff($data, $this->search, JsonDiff::STOP_ON_DIFF);
38-
if ($diff->getDiffCnt() === 0) {
39-
return $this->replace;
52+
if ($check) {
53+
$diff = new JsonDiff($data, $this->search, JsonDiff::STOP_ON_DIFF);
54+
if ($diff->getDiffCnt() === 0) {
55+
$this->affectedPaths[] = $this->path;
56+
return $this->replace;
57+
}
4058
}
4159

4260
$result = array();

Diff for: tests/src/ReplaceTest.php

+37
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,43 @@ public function testReplace()
4141
$this->assertEquals($expected, $result);
4242
}
4343

44+
public function testReplaceFilterPath()
45+
{
46+
$data = json_decode(<<<JSON
47+
{
48+
"data": [
49+
{"a":"b","c":"d"},
50+
{"c":"d", "a":"b"},
51+
{"c":"d"}
52+
],
53+
"o":{"a":"b","c":"d"}
54+
}
55+
JSON
56+
);
57+
$replace = new JsonValueReplace(
58+
json_decode('{"a":"b","c":"d"}'),
59+
json_decode('{"a":"b","c":"d","e":"f"}'),
60+
'~.*/data/.*~'
61+
);
62+
63+
$result = $replace->process($data);
64+
$expected = json_decode(<<<JSON
65+
{
66+
"data": [
67+
{"a":"b","c":"d","e":"f"},
68+
{"c":"d", "a":"b","e":"f"},
69+
{"c":"d"}
70+
],
71+
"o":{"a":"b","c":"d"}
72+
}
73+
JSON
74+
);
75+
76+
$this->assertEquals($expected, $result);
77+
78+
$this->assertSame(array('/data/0', '/data/1'), $replace->affectedPaths);
79+
}
80+
4481

4582
public function testReplaceScalar()
4683
{

0 commit comments

Comments
 (0)