From c9719f6bc8ee5ca28e2091db0cf530d18af2460f Mon Sep 17 00:00:00 2001 From: vpoturaev Date: Sat, 28 Apr 2018 11:37:47 +0700 Subject: [PATCH] option to skip overwriting value if it is set --- src/JsonPointer.php | 8 ++++++++ tests/src/JsonPointerTest.php | 9 +++++++++ 2 files changed, 17 insertions(+) diff --git a/src/JsonPointer.php b/src/JsonPointer.php index 6ba10e7..1413cb3 100644 --- a/src/JsonPointer.php +++ b/src/JsonPointer.php @@ -15,6 +15,11 @@ class JsonPointer */ const STRICT_MODE = 2; + /** + * Skip action if holder already has a non-null value at path + */ + const SKIP_IF_ISSET = 4; + /** * @param string $key * @param bool $isURIFragmentId @@ -143,6 +148,9 @@ public static function add(&$holder, $pathItems, $value, $flags = self::RECURSIV } } } + if ($ref !== null && $flags & self::SKIP_IF_ISSET) { + return; + } $ref = $value; } diff --git a/tests/src/JsonPointerTest.php b/tests/src/JsonPointerTest.php index 45d8a9b..9658bfd 100644 --- a/tests/src/JsonPointerTest.php +++ b/tests/src/JsonPointerTest.php @@ -17,6 +17,15 @@ public function testProcess() JsonPointer::add($json, ['l1','l2','l3'], 'hello!'); $this->assertSame('{"l1":{"l2":{"l3":"hello!"}}}', json_encode($json)); + JsonPointer::add($json, ['l1', 'l2', 'l3'], 'hello again!', JsonPointer::SKIP_IF_ISSET); + $this->assertSame('{"l1":{"l2":{"l3":"hello!"}}}', json_encode($json)); + + JsonPointer::add($json, ['l1', 'l2', 'l3'], 'hello again!'); + $this->assertSame('{"l1":{"l2":{"l3":"hello again!"}}}', json_encode($json)); + + JsonPointer::add($json, ['l1', 'l2', 'l3'], 'hello!'); + $this->assertSame('{"l1":{"l2":{"l3":"hello!"}}}', json_encode($json)); + $this->assertSame('{"l3":"hello!"}', json_encode(JsonPointer::get($json, JsonPointer::splitPath('/l1/l2')))); try {