Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use order-agnostic comparison for JSON #383

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 11 additions & 12 deletions src/Venturecraft/Revisionable/RevisionableTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,13 +128,15 @@ public function preSave()
foreach ($this->updatedData as $key => $val) {
$castCheck = ['object', 'array'];
if (isset($this->casts[$key]) && in_array(gettype($val), $castCheck) && in_array($this->casts[$key], $castCheck) && isset($this->originalData[$key])) {
// Sorts the keys of a JSON object due Normalization performed by MySQL
// So it doesn't set false flag if it is changed only order of key or whitespace after comma

// Due to MySQL resorting JSON keys for efficiency, we'll ignore the change if
// only the order of keys was modified

$originalData = $this->sortJsonKeys(json_decode($this->originalData[$key], true));
$updatedData = $this->sortJsonKeys(json_decode($this->updatedData[$key], true));

$this->updatedData[$key] = json_encode($updatedData);
$this->originalData[$key] = json_encode(json_decode($this->originalData[$key], true));

if ($originalData === $updatedData) {
$this->syncOriginalAttribute($key);
}
} else if (gettype($val) == 'object' && !method_exists($val, '__toString')) {
unset($this->originalData[$key]);
unset($this->updatedData[$key]);
Expand Down Expand Up @@ -522,17 +524,14 @@ private function sortJsonKeys($attribute)
{
if(empty($attribute)) return $attribute;

foreach ($attribute as $key=>$value) {
foreach ($attribute as &$value) {
if(is_array($value) || is_object($value)){
$value = $this->sortJsonKeys($value);
} else {
continue;
}

ksort($value);
$attribute[$key] = $value;
}

ksort($attribute);

return $attribute;
}
}