Skip to content

Commit

Permalink
Merge 66b8080 into ca93d46
Browse files Browse the repository at this point in the history
  • Loading branch information
boukeversteegh committed Jan 18, 2016
2 parents ca93d46 + 66b8080 commit 58c1bfd
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Mappable.php
Expand Up @@ -50,6 +50,7 @@ public static function bootMappable()
'__isset',
'__unset',
'queryHook',
'isDirty',
] as $method) {
static::hook($method, $hooks->{$method}());
}
Expand Down
12 changes: 12 additions & 0 deletions src/Mappable/Hooks.php
Expand Up @@ -36,6 +36,18 @@ public function queryHook()
};
}

public function isDirty()
{
return function ($next, $attributes = null, $bag) {
if (is_array($attributes)) {
$attributes = array_map(function ($attribute) {
return $this->getMappingForAttribute($attribute) ?: $attribute;
}, $attributes);
}
return $next($attributes, $bag);
};
}

/**
* Register hook on save method.
*
Expand Down
42 changes: 42 additions & 0 deletions tests/MappableTest.php
Expand Up @@ -383,6 +383,48 @@ public function it_sets_mapped_value()
$this->assertEquals('new_bam_value', $this->model->mapAttribute('bam'));
}

/**
* @test
* @covers \Sofa\Eloquence\Mappable\Hooks::isDirty
*/
public function mapped_attribute_is_dirty()
{
// $model->nick maps to $model->ign
$model = $this->getModel();
$model->nick = 'foo';

$this->assertTrue($model->isDirty(), 'model should be dirty when mapped attribute is changed');
$this->assertTrue($model->isDirty('nick'), 'mapped attribute should be dirty when changed');
$this->assertTrue($model->isDirty('ign'), 'original attribute should be dirty when mapped attribute is changed');

unset($model->nick);

$this->assertFalse($model->isDirty('nick'), 'mapped attribute should no longer be dirty');
$this->assertFalse($model->isDirty('ign'), 'original attribute should no longer be dirty');
}

/**
* @test
* @covers \Sofa\Eloquence\Mappable\Hooks::isDirty
*/
public function mapped_attributes_multiple_is_dirty()
{
// $model->nick maps to $model->ign
$model = $this->getModel();
$model->nick = 'foo';

$this->assertFalse($model->isDirty('foo', 'bar'), 'should be clean when affected attributes are excluded');
$this->assertFalse($model->isDirty(['foo', 'bar']), 'should be clean when affected attributes are excluded');

$this->assertTrue($model->isDirty('bar', 'nick'), 'should be dirty when affected attribute is included');
$this->assertTrue($model->isDirty(['bar', 'nick']), 'should be dirty when affected attribute is included');

unset($model->nick);

$this->assertFalse($model->isDirty('nick', 'foo'), 'should not be dirty after affected attributed is cleared');
$this->assertFalse($model->isDirty('ign', 'foo'), 'should not be dirty after affected attributed is cleared');
}

public function getModel()
{
$model = new MappableEloquentStub;
Expand Down

0 comments on commit 58c1bfd

Please sign in to comment.