Last active
August 29, 2015 14:10
-
-
Save jacobemcken/1677d320bcef1a3ca3de to your computer and use it in GitHub Desktop.
Unit test for Laravel custom validator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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