Skip to content

Commit

Permalink
Fixing isUnique and extistsIn rules when updating entities
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Dec 6, 2014
1 parent 9da7e9d commit 3b1041f
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/ORM/Rule/ExistsIn.php
Expand Up @@ -61,6 +61,10 @@ public function __invoke(EntityInterface $entity, array $options) {
$this->_repository = $options['repository']->association($this->_repository);
}

if (!$entity->extract($this->_fields, true)) {
return true;
}

$conditions = array_combine(
(array)$this->_repository->primaryKey(),
$entity->extract($this->_fields)
Expand Down
4 changes: 4 additions & 0 deletions src/ORM/Rule/IsUnique.php
Expand Up @@ -46,6 +46,10 @@ public function __construct(array $fields) {
* @return bool
*/
public function __invoke(EntityInterface $entity, array $options) {
if (!$entity->extract($this->_fields, true)) {
return true;
}

$conditions = $entity->extract($this->_fields);
if ($entity->isNew() === false) {
$keys = (array)$options['repository']->primaryKey();
Expand Down
38 changes: 38 additions & 0 deletions tests/TestCase/ORM/RulesCheckerIntegrationTest.php
Expand Up @@ -451,4 +451,42 @@ public function testUseBuildRulesEvent() {
$this->assertFalse($table->save($entity));
}

/**
* Tests isUnique with untouched fields
*
* @group save
* @return void
*/
public function testIsUniqueWithCleanFields() {
$table = TableRegistry::get('Articles');
$entity = $table->get(1);
$rules = $table->rulesChecker();
$rules->add($rules->isUnique(['title', 'author_id'], 'Nope'));

$entity->body = 'Foo';
$this->assertSame($entity, $table->save($entity));

$entity->title = 'Third Article';
$this->assertFalse($table->save($entity));
}

/**
* Tests the existsIn rule when passing non dirty fields
*
* @group save
* @return void
*/
public function testExistsInWithCleanFields() {
$table = TableRegistry::get('Articles');
$table->belongsTo('Authors');
$rules = $table->rulesChecker();
$rules->add($rules->existsIn('author_id', 'Authors'));

$entity = $table->get(1);
$entity->title = 'Foo';
$entity->author_id = 1000;
$entity->dirty('author_id', false);
$this->assertSame($entity, $table->save($entity));
}

}

0 comments on commit 3b1041f

Please sign in to comment.