From ea5ae40f9fd978287cecfe5b258f541dbaf6fa49 Mon Sep 17 00:00:00 2001 From: Jose Lorenzo Rodriguez Date: Thu, 14 Nov 2013 18:40:23 +0100 Subject: [PATCH] Adding support for using closures as rules in validator --- Cake/ORM/Validation/ValidationRule.php | 8 ++++++-- Cake/Test/TestCase/ORM/ValidatorTest.php | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/Cake/ORM/Validation/ValidationRule.php b/Cake/ORM/Validation/ValidationRule.php index b0dd624fcec..cbdcfc5ae6d 100644 --- a/Cake/ORM/Validation/ValidationRule.php +++ b/Cake/ORM/Validation/ValidationRule.php @@ -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]); diff --git a/Cake/Test/TestCase/ORM/ValidatorTest.php b/Cake/Test/TestCase/ORM/ValidatorTest.php index cfe07674880..9d3fcece6ab 100644 --- a/Cake/Test/TestCase/ORM/ValidatorTest.php +++ b/Cake/Test/TestCase/ORM/ValidatorTest.php @@ -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 *