Skip to content

Commit 44b7078

Browse files
committed
do not modify data on failing add
1 parent cc847b3 commit 44b7078

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/JsonPointer.php

+9-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,15 @@ public static function add(&$holder, $pathItems, $value, $recursively = true)
7575
Exception::EMPTY_PROPERTY_NAME_UNSUPPORTED);
7676
}
7777

78-
$ref = &$ref->$key;
78+
if ($recursively) {
79+
$ref = &$ref->$key;
80+
} else {
81+
if (!isset($ref->$key) && count($pathItems)) {
82+
throw new Exception('Non-existent path item: ' . $key);
83+
} else {
84+
$ref = &$ref->$key;
85+
}
86+
}
7987
} else { // null or array
8088
$intKey = filter_var($key, FILTER_VALIDATE_INT);
8189
if ($ref === null && (false === $intKey || $intKey !== 0)) {

tests/src/JsonPatchTest.php

+19
Original file line numberDiff line numberDiff line change
@@ -123,4 +123,23 @@ public function testApplyContinueOnError()
123123
$this->assertSame('Key not found: missing2', $errors[1]->getMessage());
124124
}
125125

126+
127+
public function testApplyNonExistentLevelTwo()
128+
{
129+
$data = new \stdClass();
130+
$p = new JsonPatch();
131+
$p->op(new JsonPatch\Add('/some/path', 22));
132+
$p->apply($data, false);
133+
$this->assertEquals(new \stdClass(), $data);
134+
}
135+
136+
public function testApplyNonExistentLevelOne()
137+
{
138+
$data = new \stdClass();
139+
$p = new JsonPatch();
140+
$p->op(new JsonPatch\Add('/some', 22));
141+
$p->apply($data);
142+
$this->assertEquals((object)array('some' => 22), $data);
143+
}
144+
126145
}

0 commit comments

Comments
 (0)