Skip to content

Commit

Permalink
Implementing 'on' key in ValidationRule to accept closures
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Nov 20, 2013
1 parent d5c4637 commit ce4684b
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 16 deletions.
40 changes: 24 additions & 16 deletions Cake/ORM/Validation/ValidationRule.php
Expand Up @@ -78,21 +78,6 @@ public function __construct($validator = array()) {
$this->_addValidatorProps($validator);
}

/**
* Checks if the validation rule should be skipped
*
* @param boolean $newRecord whether the rule to be processed is new or pre-existent
* @return boolean True if the ValidationRule should be skipped
*/
public function skip($newRecord) {
if (!empty($this->_on)) {
if ($this->_on === 'create' && !$newRecord || $this->_on === 'update' && $newRecord) {
return true;
}
}
return false;
}

/**
* Returns whether this rule should break validation process for associated field
* after it fails
Expand All @@ -118,7 +103,7 @@ public function isLast() {
* callable for the configured scope
*/
public function process($data, $scopes, $newRecord) {
if ($this->skip($newRecord)) {
if ($this->_skip($newRecord, $scopes)) {
return true;
}

Expand Down Expand Up @@ -148,6 +133,29 @@ public function process($data, $scopes, $newRecord) {
return $result;
}

/**
* Checks if the validation rule should be skipped
*
* @param boolean $newRecord whether the rule to be processed is new or pre-existent
* @param array $scopes associative array with objects or class names that will
* be passed as the last argument for the validation method
* @return boolean True if the ValidationRule should be skipped
*/
protected function _skip($newRecord, $scopes) {
if (is_callable($this->_on)) {
$function = $this->_on;
return !$function($scopes);
}

if (!empty($this->_on)) {
if ($this->_on === 'create' && !$newRecord || $this->_on === 'update' && $newRecord) {
return true;
}
}
return false;
}


/**
* Sets the rule properties from the rule entry in validate
*
Expand Down
28 changes: 28 additions & 0 deletions Cake/Test/TestCase/ORM/Validation/ValidationRuleTest.php
Expand Up @@ -119,4 +119,32 @@ public function testSkip() {
]);
$this->assertFalse($Rule->process($data, $scopes, false));
}

/**
* Tests that the 'on' key can be a callable function
*
* @return void
*/
public function testCallableOn() {
$data = 'some data';
$scopes = ['default' => $this];

$Rule = new ValidationRule([
'rule' => 'myTestRule',
'on' => function($s) use ($scopes) {
$this->assertEquals($scopes, $s);
return true;
}
]);
$this->assertFalse($Rule->process($data, $scopes, true));

$Rule = new ValidationRule([
'rule' => 'myTestRule',
'on' => function($s) use ($scopes) {
$this->assertEquals($scopes, $s);
return false;
}
]);
$this->assertTrue($Rule->process($data, $scopes, true));
}
}

0 comments on commit ce4684b

Please sign in to comment.