From 6c665c773e75d72475da164a08132a7ffea71895 Mon Sep 17 00:00:00 2001 From: Jose Lorenzo Rodriguez Date: Sun, 30 Nov 2014 17:43:06 +0100 Subject: [PATCH] Adding IsUnique reusable domain rule --- src/ORM/DomainChecker.php | 5 +++ src/ORM/Rule/IsUnique.php | 39 +++++++++++++++++++ .../ORM/DomainRulesIntegrationTest.php | 21 ++++++++++ 3 files changed, 65 insertions(+) create mode 100644 src/ORM/Rule/IsUnique.php diff --git a/src/ORM/DomainChecker.php b/src/ORM/DomainChecker.php index b9e230be483..2823d904333 100644 --- a/src/ORM/DomainChecker.php +++ b/src/ORM/DomainChecker.php @@ -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 @@ -65,4 +66,8 @@ public function checkUpdate(EntityInterface $entity) { return $success; } + public function isUnique(array $fields) { + return new IsUnique($fields); + } + } diff --git a/src/ORM/Rule/IsUnique.php b/src/ORM/Rule/IsUnique.php new file mode 100644 index 00000000000..48625ccfea8 --- /dev/null +++ b/src/ORM/Rule/IsUnique.php @@ -0,0 +1,39 @@ +_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); + } + +} diff --git a/tests/TestCase/ORM/DomainRulesIntegrationTest.php b/tests/TestCase/ORM/DomainRulesIntegrationTest.php index 71c8dc7f7d2..a0ab9a965a5 100644 --- a/tests/TestCase/ORM/DomainRulesIntegrationTest.php +++ b/tests/TestCase/ORM/DomainRulesIntegrationTest.php @@ -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)); + } + }