From 67f2acf347ad6da6892d537da001835ca5a840c1 Mon Sep 17 00:00:00 2001 From: vpoturaev Date: Thu, 15 Mar 2018 18:13:39 +0700 Subject: [PATCH] JsonValueReplace --- src/JsonValueReplace.php | 28 +++++++++++++++++++++++----- tests/src/ReplaceTest.php | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 5 deletions(-) diff --git a/src/JsonValueReplace.php b/src/JsonValueReplace.php index e27cb39..2088c68 100644 --- a/src/JsonValueReplace.php +++ b/src/JsonValueReplace.php @@ -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; } /** @@ -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(); diff --git a/tests/src/ReplaceTest.php b/tests/src/ReplaceTest.php index 64eda34..62ab75d 100644 --- a/tests/src/ReplaceTest.php +++ b/tests/src/ReplaceTest.php @@ -41,6 +41,43 @@ public function testReplace() $this->assertEquals($expected, $result); } + public function testReplaceFilterPath() + { + $data = json_decode(<<process($data); + $expected = json_decode(<<assertEquals($expected, $result); + + $this->assertSame(array('/data/0', '/data/1'), $replace->affectedPaths); + } + public function testReplaceScalar() {