Skip to content

Commit

Permalink
Merge pull request #37 from Weebly/fix-original
Browse files Browse the repository at this point in the history
Properly unserialize `getOriginal` values
  • Loading branch information
kchung authored Oct 16, 2024
2 parents 7ceb9b6 + 3384db1 commit 04d6a1d
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
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

0 comments on commit 04d6a1d

Please sign in to comment.