Skip to content

Commit 3b1041f

Browse files
committed
Fixing isUnique and extistsIn rules when updating entities
1 parent 9da7e9d commit 3b1041f

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

src/ORM/Rule/ExistsIn.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,10 @@ public function __invoke(EntityInterface $entity, array $options) {
6161
$this->_repository = $options['repository']->association($this->_repository);
6262
}
6363

64+
if (!$entity->extract($this->_fields, true)) {
65+
return true;
66+
}
67+
6468
$conditions = array_combine(
6569
(array)$this->_repository->primaryKey(),
6670
$entity->extract($this->_fields)

src/ORM/Rule/IsUnique.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,10 @@ public function __construct(array $fields) {
4646
* @return bool
4747
*/
4848
public function __invoke(EntityInterface $entity, array $options) {
49+
if (!$entity->extract($this->_fields, true)) {
50+
return true;
51+
}
52+
4953
$conditions = $entity->extract($this->_fields);
5054
if ($entity->isNew() === false) {
5155
$keys = (array)$options['repository']->primaryKey();

tests/TestCase/ORM/RulesCheckerIntegrationTest.php

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -451,4 +451,42 @@ public function testUseBuildRulesEvent() {
451451
$this->assertFalse($table->save($entity));
452452
}
453453

454+
/**
455+
* Tests isUnique with untouched fields
456+
*
457+
* @group save
458+
* @return void
459+
*/
460+
public function testIsUniqueWithCleanFields() {
461+
$table = TableRegistry::get('Articles');
462+
$entity = $table->get(1);
463+
$rules = $table->rulesChecker();
464+
$rules->add($rules->isUnique(['title', 'author_id'], 'Nope'));
465+
466+
$entity->body = 'Foo';
467+
$this->assertSame($entity, $table->save($entity));
468+
469+
$entity->title = 'Third Article';
470+
$this->assertFalse($table->save($entity));
471+
}
472+
473+
/**
474+
* Tests the existsIn rule when passing non dirty fields
475+
*
476+
* @group save
477+
* @return void
478+
*/
479+
public function testExistsInWithCleanFields() {
480+
$table = TableRegistry::get('Articles');
481+
$table->belongsTo('Authors');
482+
$rules = $table->rulesChecker();
483+
$rules->add($rules->existsIn('author_id', 'Authors'));
484+
485+
$entity = $table->get(1);
486+
$entity->title = 'Foo';
487+
$entity->author_id = 1000;
488+
$entity->dirty('author_id', false);
489+
$this->assertSame($entity, $table->save($entity));
490+
}
491+
454492
}

0 commit comments

Comments
 (0)