Merge pull request #161 from vlucas/withdata

Added withData method for immutable reusability
This commit is contained in:
Willem Wollebrants 2016-08-17 21:48:04 +02:00 committed by GitHub
commit 6200b45304
2 changed files with 29 additions and 1 deletions

View File

@ -1085,4 +1085,19 @@ class Validator
}
}
}
/**
* Replace data on cloned instance
*
* @param array $data
* @param array $fields
* @return Valitron
*/
public function withData($data, $fields = array())
{
$clone = clone $this;
$clone->reset();
$clone->_fields = !empty($fields) ? array_intersect_key($data, array_flip($fields)) : $data;
return $clone;
}
}

View File

@ -1156,6 +1156,19 @@ class ValidateTest extends BaseTestCase
$v->rule('optional', 'address')->rule('email', 'address');
$this->assertTrue($v->validate());
}
public function testWithData()
{
$v = new Validator(array());
$v->rule('required', 'name');
//validation failed, so must have errors
$this->assertFalse($v->validate());
$this->assertNotEmpty($v->errors());
//create copy with different data
$v2 = $v->withData(array('name' => 'Chester Tester'));
$this->assertTrue($v2->validate());
$this->assertEmpty($v2->errors());
}
}
function sampleFunctionCallback($field, $value, array $params) {