Skip to content

Commit

Permalink
Adding IsUnique reusable domain rule
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Nov 30, 2014
1 parent f6fd04d commit 6c665c7
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/ORM/DomainChecker.php
Expand Up @@ -15,6 +15,7 @@
namespace Cake\ORM;

use Cake\Datasource\EntityInterface;
use Cake\ORM\Rule\IsUnique;

/**
* Contains logic for storing and checking domain rules on entities
Expand Down Expand Up @@ -65,4 +66,8 @@ public function checkUpdate(EntityInterface $entity) {
return $success;
}

public function isUnique(array $fields) {
return new IsUnique($fields);
}

}
39 changes: 39 additions & 0 deletions src/ORM/Rule/IsUnique.php
@@ -0,0 +1,39 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\ORM\Rule;

use Cake\Datasource\EntityInterface;

/**
*
*
*/
class IsUnique {

public function __construct(array $fields) {
$this->_fields = $fields;
}

public function __invoke(EntityInterface $entity, array $options) {
$conditions = $entity->extract($this->_fields);
if ($entity->isNew() === false) {
$keys = (array)$options['repository']->primaryKey();
$conditions['NOT'] = $entity->extract($keys);
}

return !$options['repository']->exists($conditions);
}

}
21 changes: 21 additions & 0 deletions tests/TestCase/ORM/DomainRulesIntegrationTest.php
Expand Up @@ -278,4 +278,25 @@ public function testSaveBelongsToManyWithValidationErrorInJointEntityNonAtomic()
$this->assertEquals(5, $entity->tags[1]->_joinData->tag_id);
}

/**
* Tests the isUnique domain rule
*
* @group save
* @return void
*/
public function testIsUniqueDomainRule() {
$entity = new Entity([
'name' => 'larry'
]);

$table = TableRegistry::get('Authors');
$rules = $table->domainRules();
$rules->add($rules->isUnique(['name']));

$this->assertFalse($table->save($entity));

$entity->name = 'jose';
$this->assertSame($entity, $table->save($entity));
}

}

0 comments on commit 6c665c7

Please sign in to comment.