-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Extract json patch to mongo update logic to a separate method.
- Loading branch information
Showing
2 changed files
with
63 additions
and
48 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
<?php | ||
namespace Makasim\Yadm; | ||
|
||
class Converter | ||
{ | ||
/** | ||
* @param array $diff | ||
* | ||
* @return array | ||
*/ | ||
public static function convertJsonPatchToMongoUpdate(array $diff) | ||
{ | ||
$update = ['$set' => [], '$unset' => []]; | ||
foreach ($diff as $op) { | ||
switch ($op['op']) { | ||
case 'add': | ||
if (is_array($op['value'])) { | ||
foreach ($op['value'] as $key => $value) { | ||
$update['$set'][self::pathToDot($op['path']).'.'.$key] = $value; | ||
} | ||
} else { | ||
$update['$set'][self::pathToDot($op['path'])] = $op['value']; | ||
} | ||
|
||
break; | ||
case 'remove': | ||
$update['$unset'][self::pathToDot($op['path'])] = ''; | ||
|
||
break; | ||
case 'replace': | ||
$update['$set'][self::pathToDot($op['path'])] = $op['value']; | ||
|
||
break; | ||
default: | ||
throw new \LogicException('JSON Patch operation "'.$op['op'].'"" is not supported.'); | ||
} | ||
|
||
|
||
} | ||
|
||
if (empty($update['$set'])) { | ||
unset($update['$set']); | ||
} | ||
if (empty($update['$unset'])) { | ||
unset($update['$unset']); | ||
} | ||
|
||
return $update; | ||
} | ||
|
||
/** | ||
* @param string $path | ||
* | ||
* @return string | ||
*/ | ||
private static function pathToDot($path) | ||
{ | ||
$path = ltrim($path, '/'); | ||
|
||
return str_replace('/', '.', $path); | ||
} | ||
} |