Skip to content

Commit

Permalink
Extract json patch to mongo update logic to a separate method.
Browse files Browse the repository at this point in the history
  • Loading branch information
makasim committed Mar 13, 2017
1 parent 1093a85 commit c975a77
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 48 deletions.
49 changes: 1 addition & 48 deletions src/ChangesCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,53 +34,6 @@ public function changes($object)

$diff = JsonPatch::diff($this->originalValues[$id], get_values($object));

$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'][$this->pathToDot($op['path']).'.'.$key] = $value;
}
} else {
$update['$set'][$this->pathToDot($op['path'])] = $op['value'];
}

break;
case 'remove':
$update['$unset'][$this->pathToDot($op['path'])] = '';

break;
case 'replace':
$update['$set'][$this->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 function pathToDot($path)
{
$path = ltrim($path, '/');

return str_replace('/', '.', $path);
return Converter::convertJsonPatchToMongoUpdate($diff);
}
}
62 changes: 62 additions & 0 deletions src/Converter.php
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);
}
}

0 comments on commit c975a77

Please sign in to comment.