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

Properly unserialize getOriginal values #37

Merged
merged 3 commits into from
Oct 16, 2024
Merged
Show file tree
Hide file tree
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
24 changes: 24 additions & 0 deletions src/Database/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,30 @@ public function attributesToArray()
return $attributes;
}

/**
* {@inheritdoc}
*/
public function getOriginal($key = null, $default = null)
{
$original = parent::getOriginal($key, $default);

if ($key) {
if ($this->hasMutator($key)) {
return $this->unserializeAttribute($key, $original);
}

return $original;
}

foreach ($original as $attribute => $value) {
if ($this->hasMutator($attribute)) {
$original[$attribute] = $this->unserializeAttribute($attribute, $value);
}
}

return $original;
}

/**
* Define a many-to-many relationship.
*
Expand Down
42 changes: 41 additions & 1 deletion tests/Unit/Database/Traits/HasMutatorsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ public function testSerializeAttribute()

public function testUnserializeAttribute()
{
$uuid = 'cf98906e-9074-11e7-9c8e-437b4bab8527';
$mutator = M::mock(MutatorContract::class)
->shouldReceive('get')
->with('test_mutator')
Expand All @@ -52,6 +51,47 @@ public function testUnserializeAttribute()
$this->assertEquals('serialized_attribute', $model->id);
}

public function testGetOriginal()
{
$mutator = M::mock(MutatorContract::class)
->shouldReceive('get')
->with('test_mutator')
->andReturnSelf()
->once()
->shouldReceive('unserializeAttribute')
->with('unserialized_attribute')
->andReturn('serialized_attribute')
->once()
->getMock();

app()['mutator'] = $mutator;

$model = new SampleModel();
$original = $model->getOriginal();

$this->assertIsArray($original);
$this->assertEquals('serialized_attribute', $original['id']);
}

public function testGetOriginalProperty()
{
$mutator = M::mock(MutatorContract::class)
->shouldReceive('get')
->with('test_mutator')
->andReturnSelf()
->once()
->shouldReceive('unserializeAttribute')
->with('unserialized_attribute')
->andReturn('serialized_attribute')
->once()
->getMock();

app()['mutator'] = $mutator;

$model = new SampleModel();
$this->assertEquals('serialized_attribute', $model->getOriginal('id'));
}

public function testGetMutators()
{
$this->assertEquals(['id' => 'test_mutator'], (new SampleModel())->getMutators());
Expand Down
Loading