Skip to content

Commit

Permalink
Move model data serialization and deserialization to separate methods
Browse files Browse the repository at this point in the history
This allows extending the Version class and changing the migration
to store model data differently

Implements mpociot#44
  • Loading branch information
Yaohan Chen committed Nov 16, 2018
1 parent 536c732 commit 7051fab
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
26 changes: 21 additions & 5 deletions src/Mpociot/Versionable/Version.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,9 @@ public function getResponsibleUserAttribute()
*/
public function getModel()
{
$modelData = is_resource($this->model_data)
? stream_get_contents($this->model_data)
: $this->model_data;

$model = new $this->versionable_type();
$model->unguard();
$model->fill(unserialize($modelData));
$model->fill($this->modelData());
$model->exists = true;
$model->reguard();
return $model;
Expand Down Expand Up @@ -104,4 +100,24 @@ public function diff(Version $againstVersion = null)
return $diffArray;
}

/**
* Copy attributes of a model to be saved with the version
*
* @param Model $model
*/
public function copyModelData(Model $model)
{
$this->model_data = serialize($model->getAttributes());
}

/**
* Model attributes
*/
protected function modelData()
{
$serialized = is_resource($this->model_data)
? stream_get_contents($this->model_data)
: $this->model_data;
return unserialize($serialized);
}
}
2 changes: 1 addition & 1 deletion src/Mpociot/Versionable/VersionableTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ protected function versionablePostSave()
$version->versionable_id = $this->getKey();
$version->versionable_type = get_class($this);
$version->user_id = $this->getAuthUserId();
$version->model_data = serialize($this->getAttributes());
$version->copyModelData($this);

if (!empty( $this->reason )) {
$version->reason = $this->reason;
Expand Down

0 comments on commit 7051fab

Please sign in to comment.