Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 960918e

Browse files
author
Allen Tsai
committedMar 22, 2018
Handle Array/Object Conversion
This commit allows us to patch from an empty "array" into an object. Without this commit: ``` $old = ["emptyObject" => []]; $new = ["emptyObject" => ["notEmpty"=>"value"]]; $diff = new \Swaggest\JsonDiff\JsonDiff(json_decode(json_encode($old)), json_decode(json_encode($new))); $patch = $diff->getPatch(); $test = json_decode(json_encode($old)); $patch->apply($test); ``` fails
1 parent 94925ea commit 960918e

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed
 

‎src/JsonPointer.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,9 @@ public static function add(&$holder, $pathItems, $value, $recursively = true)
108108
} else {
109109
throw new Exception('Non-existent path item: ' . $key);
110110
}
111+
} elseif ([] === $ref && false === $intKey && '-' !== $key) {
112+
$ref = new \stdClass();
113+
$ref = &$ref->{$key};
111114
} else {
112115
if ($recursively && $ref === null) $ref = array();
113116
if ('-' === $key) {
@@ -244,4 +247,4 @@ public static function remove(&$holder, $pathItems)
244247
}
245248
return $ref;
246249
}
247-
}
250+
}

‎tests/src/Issues/Issue9Test.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?php
2+
3+
namespace Swaggest\JsonDiff\Tests\Issues;
4+
5+
use Swaggest\JsonDiff\JsonDiff;
6+
7+
/**
8+
* @see https://github.com/swaggest/json-diff/issues/9
9+
*/
10+
class Issue9Test extends \PHPUnit_Framework_TestCase
11+
{
12+
public function testPatchApply()
13+
{
14+
$old = json_decode(json_encode(["emptyObject" => []]));
15+
$new = json_decode(json_encode(["emptyObject" => ["notEmpty"=>"value"]]));
16+
$diff = new JsonDiff($old, $new);
17+
$patch = $diff->getPatch();
18+
$this->assertNotEquals($new, $old);
19+
$patch->apply($old);
20+
$this->assertEquals($new, $old);
21+
}
22+
}

0 commit comments

Comments
 (0)
Please sign in to comment.