Skip to content

Commit

Permalink
Adding support for using closures as rules in validator
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Nov 20, 2013
1 parent 37dc016 commit ea5ae40
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
8 changes: 6 additions & 2 deletions Cake/ORM/Validation/ValidationRule.php
Expand Up @@ -115,8 +115,12 @@ public function isLast() {
* @return boolean|string
*/
public function process($data, $scopes, $newRecord) {
$scope = $scopes[$this->_scope];
$callable = [$scope, $this->_rule];
if (is_callable($this->_rule)) {
$callable = $this->_rule;
} else {
$scope = $scopes[$this->_scope];
$callable = [$scope, $this->_rule];
}

if ($this->_pass) {
$args = array_merge([$data], $this->_pass, [$scopes]);
Expand Down
17 changes: 17 additions & 0 deletions Cake/Test/TestCase/ORM/ValidatorTest.php
Expand Up @@ -313,6 +313,23 @@ public function testMethodsWithExtraArguments() {
$this->assertEquals($expected, $errors);
}

/**
* Tests that it is possible to use a closure as a rule
*
* @return void
*/
public function testUsingClosureAsRule() {
$validator = new Validator;
$validator->add('name', 'myRule', [
'rule' => function($data, $scopes) {
$this->assertEquals('foo', $data);
return 'You fail';
}
]);
$expected = ['name' => ['myRule' => 'You fail']];
$this->assertEquals($expected, $validator->errors(['name' => 'foo']));
}

/**
* Tests that setting last to a rule will stop validating the rest of the rules
*
Expand Down

0 comments on commit ea5ae40

Please sign in to comment.