Skip to content

Commit

Permalink
do not modify data on failing add
Browse files Browse the repository at this point in the history
  • Loading branch information
vearutop committed Mar 19, 2018
1 parent cc847b3 commit 44b7078
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/JsonPointer.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,15 @@ public static function add(&$holder, $pathItems, $value, $recursively = true)
Exception::EMPTY_PROPERTY_NAME_UNSUPPORTED);
}

$ref = &$ref->$key;
if ($recursively) {
$ref = &$ref->$key;
} else {
if (!isset($ref->$key) && count($pathItems)) {
throw new Exception('Non-existent path item: ' . $key);
} else {
$ref = &$ref->$key;
}
}
} else { // null or array
$intKey = filter_var($key, FILTER_VALIDATE_INT);
if ($ref === null && (false === $intKey || $intKey !== 0)) {
Expand Down
19 changes: 19 additions & 0 deletions tests/src/JsonPatchTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,4 +123,23 @@ public function testApplyContinueOnError()
$this->assertSame('Key not found: missing2', $errors[1]->getMessage());
}


public function testApplyNonExistentLevelTwo()
{
$data = new \stdClass();
$p = new JsonPatch();
$p->op(new JsonPatch\Add('/some/path', 22));
$p->apply($data, false);
$this->assertEquals(new \stdClass(), $data);
}

public function testApplyNonExistentLevelOne()
{
$data = new \stdClass();
$p = new JsonPatch();
$p->op(new JsonPatch\Add('/some', 22));
$p->apply($data);
$this->assertEquals((object)array('some' => 22), $data);
}

}

0 comments on commit 44b7078

Please sign in to comment.