fix array structure to make it easier to parse. update tests

This commit is contained in:
Joel Clermont 2013-03-05 17:12:42 -06:00
parent 035de87cf7
commit 173ad40b7d
2 changed files with 31 additions and 18 deletions

View File

@ -515,25 +515,14 @@ class Validator
public function rules($rules) public function rules($rules)
{ {
foreach ($rules as $ruleType => $params) { foreach ($rules as $ruleType => $params) {
if (is_array($params) && !empty($params)) { if (is_array($params)) {
// differentiate between a single rule taking an array of params
// and an array of rules within a single type
if (count($params) > 1 && is_array($params[0]) && is_array($params[1])) {
foreach ($params as $innerParams) { foreach ($params as $innerParams) {
$this->callRuleWithParams($ruleType, $innerParams); array_unshift($innerParams, $ruleType);
} call_user_func_array(array($this, "rule"), $innerParams);
} else {
$this->callRuleWithParams($ruleType, $params);
} }
} else { } else {
$this->rule($ruleType, $params); $this->rule($ruleType, $params);
} }
} }
} }
protected function callRuleWithParams($ruleType, $params)
{
array_unshift($params, $ruleType);
call_user_func_array(array($this, 'rule'), $params);
}
} }

View File

@ -421,9 +421,15 @@ class ValidateTest extends \PHPUnit_Framework_TestCase
public function testAcceptBulkRulesWithMultipleParams() public function testAcceptBulkRulesWithMultipleParams()
{ {
$rules = array( $rules = array(
'required' => array(array('nonexistent_field', 'other_missing_field')), 'required' => array(
'equals' => array('foo', 'bar'), array(array('nonexistent_field', 'other_missing_field'))
'length' => array('foo', 5) ),
'equals' => array(
array('foo', 'bar')
),
'length' => array(
array('foo', 5)
)
); );
$v1 = new Validator(array('foo' => 'bar', 'bar' => 'baz')); $v1 = new Validator(array('foo' => 'bar', 'bar' => 'baz'));
@ -481,5 +487,23 @@ class ValidateTest extends \PHPUnit_Framework_TestCase
$this->assertEquals($v1->errors(), $v2->errors()); $this->assertEquals($v1->errors(), $v2->errors());
} }
public function testAcceptBulkRulesWithMultipleArrayParams()
{
$rules = array(
'in' => array(
array(array('foo', 'bar'), array('x', 'y'))
)
);
$v1 = new Validator(array('foo' => 'bar', 'bar' => 'baz', 'baz' => 'foo'));
$v1->rules($rules);
$v1->validate();
$v2 = new Validator(array('foo' => 'bar', 'bar' => 'baz', 'baz' => 'foo'));
$v2->rule('in', array('foo', 'bar'), array('x', 'y'));
$v2->validate();
$this->assertEquals($v1->errors(), $v2->errors());
}
} }