Skip to content
Permalink
Browse files

String return values from rules should trigger errors.

This makes rules and validation more consistent. Returning a string from
a rule always triggers a validation failure, but only when the
errorField is defined does an error message get populated.

Refs #6181
  • Loading branch information...
markstory committed Mar 31, 2015
1 parent 584a0d8 commit cb308f0c5e6c486401314b17e4a8a6531d4b7849
Showing with 55 additions and 6 deletions.
  1. +11 −6 src/ORM/RulesChecker.php
  2. +44 −0 tests/TestCase/ORM/RulesCheckerIntegrationTest.php
@@ -376,19 +376,24 @@ protected function _addError($rule, $name, $options)
return function ($entity, $scope) use ($rule, $name, $options) {
$pass = $rule($entity, $options + $scope);
if ($pass || empty($options['errorField'])) {
return $pass;
if ($pass === true || empty($options['errorField'])) {
return $pass === true;
}
$message = isset($options['message']) ? $options['message'] : 'invalid';
$message = 'invalid';
if (isset($options['message'])) {
$message = $options['message'];
}
if (is_string($pass)) {
$message = $pass;
}
if ($name) {
$message = [$name => $message];
} else {
$message = (array)$message;
$message = [$message];
}
$entity->errors($options['errorField'], $message);
return $pass;
return $pass === true;
};
}
}
@@ -715,6 +715,50 @@ public function testCustomOptionsPassingDelete()
$this->assertFalse($table->delete($entity, ['foo' => 'bar']));
}
/**
* Test adding rules that return error string
*
* @group save
* @return void
*/
public function testCustomErrorMessageFromRule()
{
$entity = new Entity([
'name' => 'larry'
]);
$table = TableRegistry::get('Authors');
$rules = $table->rulesChecker();
$rules->add(function () {
return 'So much nope';
}, ['errorField' => 'name']);
$this->assertFalse($table->save($entity));
$this->assertEquals(['So much nope'], $entity->errors('name'));
}
/**
* Test adding rules with no errorField do not accept strings
*
* @group save
* @return void
*/
public function testCustomErrorMessageFromRuleNoErrorField()
{
$entity = new Entity([
'name' => 'larry'
]);
$table = TableRegistry::get('Authors');
$rules = $table->rulesChecker();
$rules->add(function () {
return 'So much nope';
});
$this->assertFalse($table->save($entity));
$this->assertEmpty($entity->errors());
}
/**
* Tests that using existsIn for a hasMany association will not be called
* as the foreign key for the association was automatically validated already.

0 comments on commit cb308f0

Please sign in to comment.
You can’t perform that action at this time.