Skip to content

Commit

Permalink
JsonValueReplace
Browse files Browse the repository at this point in the history
  • Loading branch information
vearutop committed Mar 15, 2018
1 parent 4e76cd7 commit 67f2acf
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 5 deletions.
28 changes: 23 additions & 5 deletions src/JsonValueReplace.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,23 @@ class JsonValueReplace
{
private $search;
private $replace;
private $pathFilterRegex;
private $path = '';
private $pathItems = array();

public $affectedPaths = array();

/**
* JsonReplace constructor.
* @param mixed $search
* @param mixed $replace
* @param null|string $pathFilter Regular expression to check path
*/
public function __construct($search, $replace)
public function __construct($search, $replace, $pathFilter = null)
{
$this->search = $search;
$this->replace = $replace;
$this->pathFilterRegex = $pathFilter;
}

/**
Expand All @@ -28,15 +33,28 @@ public function __construct($search, $replace)
*/
public function process($data)
{
$check = true;
if ($this->pathFilterRegex && !preg_match($this->pathFilterRegex, $this->path)) {
$check = false;
}

if (!is_array($data) && !is_object($data)) {
return $data === $this->search ? $this->replace : $data;
if ($check && $data === $this->search) {
$this->affectedPaths[] = $this->path;
return $this->replace;
} else {
return $data;
}
}

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

$diff = new JsonDiff($data, $this->search, JsonDiff::STOP_ON_DIFF);
if ($diff->getDiffCnt() === 0) {
return $this->replace;
if ($check) {
$diff = new JsonDiff($data, $this->search, JsonDiff::STOP_ON_DIFF);
if ($diff->getDiffCnt() === 0) {
$this->affectedPaths[] = $this->path;
return $this->replace;
}
}

$result = array();
Expand Down
37 changes: 37 additions & 0 deletions tests/src/ReplaceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,43 @@ public function testReplace()
$this->assertEquals($expected, $result);
}

public function testReplaceFilterPath()
{
$data = json_decode(<<<JSON
{
"data": [
{"a":"b","c":"d"},
{"c":"d", "a":"b"},
{"c":"d"}
],
"o":{"a":"b","c":"d"}
}
JSON
);
$replace = new JsonValueReplace(
json_decode('{"a":"b","c":"d"}'),
json_decode('{"a":"b","c":"d","e":"f"}'),
'~.*/data/.*~'
);

$result = $replace->process($data);
$expected = json_decode(<<<JSON
{
"data": [
{"a":"b","c":"d","e":"f"},
{"c":"d", "a":"b","e":"f"},
{"c":"d"}
],
"o":{"a":"b","c":"d"}
}
JSON
);

$this->assertEquals($expected, $result);

$this->assertSame(array('/data/0', '/data/1'), $replace->affectedPaths);
}


public function testReplaceScalar()
{
Expand Down

0 comments on commit 67f2acf

Please sign in to comment.