@@ -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 ();
0 commit comments