Skip to content

Instantly share code, notes, and snippets.

@jacobemcken
Last active August 29, 2015 14:10
Show Gist options
  • Save jacobemcken/1677d320bcef1a3ca3de to your computer and use it in GitHub Desktop.
Save jacobemcken/1677d320bcef1a3ca3de to your computer and use it in GitHub Desktop.
Unit test for Laravel custom validator
<?php
use Illuminate\Validation\Validator;
class MyValidator extends Validator {
public function validateMutuallyExclusiveWith($attribute, $value, $parameters) {
$allEmpty = true;
foreach ($parameters as $key)
{
if (!$allEmpty)
{
break;
}
$data = array_get($this->data, $parameters[0]);
$allEmpty = empty($data) || is_null($data);
}
if ($allEmpty)
{
echo "all other is empty!\n";
return $this->validateRequired($attribute, $value);
}
else
{
echo "all others is NOT empty!\n";
return !$this->validateRequired($attribute, $value);
}
}
}
<?php
class MyValidatorTest extends TestCase {
public function testMutuallyExclusiveWith()
{
$trans = $this->getRealTranslator();
$v = new MyValidator(
$trans,
['field1' => null, 'field2' => ''],
['field1' => 'mutually_exclusive_with:field2']);
$this->assertFalse($v->passes());
}
protected function getRealTranslator()
{
$trans = new Symfony\Component\Translation\Translator('en', new Symfony\Component\Translation\MessageSelector);
$trans->addLoader('array', new Symfony\Component\Translation\Loader\ArrayLoader);
return $trans;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment