Skip to content

Commit

Permalink
Merge "REST: Fix JsonPatcher return type"
Browse files Browse the repository at this point in the history
  • Loading branch information
jenkins-bot authored and Gerrit Code Review committed Oct 26, 2023
2 parents 8748887 + 52b98e1 commit c6e15b4
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 4 deletions.
5 changes: 4 additions & 1 deletion repo/rest-api/src/Domain/Services/JsonPatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,13 @@
interface JsonPatcher {

/**
* @return mixed usually this will be an array, but the type may change if the whole
* root element is modified by the client
*
* @throws InvalidArgumentException for an invalid patch
* @throws PatchPathException if a path target provided in the patch does not exist
* @throws PatchTestConditionFailedException if a "test" op in the patch fails
*/
public function patch( array $target, array $patch ): array;
public function patch( array $target, array $patch );

}
4 changes: 2 additions & 2 deletions repo/rest-api/src/Infrastructure/JsonDiffJsonPatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class JsonDiffJsonPatcher implements JsonPatcher {
/**
* @inheritDoc
*/
public function patch( array $target, array $patch ): array {
public function patch( array $target, array $patch ) {
try {
$patchDocument = JsonPatch::import( $patch );
} catch ( Exception $e ) {
Expand All @@ -41,7 +41,7 @@ public function patch( array $target, array $patch ): array {
}

// TODO investigate. Casting to array is necessary if $target starts out as an empty array.
return (array)$target;
return is_object( $target ) ? (array)$target : $target;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,12 @@ class JsonDiffJsonPatcherTest extends TestCase {

/**
* @dataProvider validPatchProvider
*
* @param array $target
* @param array $patch
* @param mixed $expected
*/
public function testPatch( array $target, array $patch, array $expected ): void {
public function testPatch( array $target, array $patch, $expected ): void {
$result = ( new JsonDiffJsonPatcher() )->patch( $target, $patch );

$this->assertEquals( $expected, $result );
Expand Down Expand Up @@ -52,6 +56,18 @@ public static function validPatchProvider(): Generator {
[ [ 'op' => 'test', 'path' => '/baz', 'value' => 42 ] ],
[ 'foo' => 'bar', 'baz' => 42 ],
];

yield 'add a key/value pair to an empty array' => [
[],
[ [ 'op' => 'add', 'path' => '/foo', 'value' => 'new value' ] ],
[ 'foo' => 'new value' ],
];

yield 'patch results in a string' => [
[ 'foo' => 'bar', 'baz' => 42 ],
[ [ 'op' => 'replace', 'path' => '', 'value' => 'replaced value' ] ],
'replaced value',
];
}

/**
Expand Down

0 comments on commit c6e15b4

Please sign in to comment.