RegexValidatorTest.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace Symfony\Tests\Component\Validator;
  3. use Symfony\Component\Validator\Constraints\Regex;
  4. use Symfony\Component\Validator\Constraints\RegexValidator;
  5. class RegexValidatorTest extends \PHPUnit_Framework_TestCase
  6. {
  7. protected $validator;
  8. protected function setUp()
  9. {
  10. $this->validator = new RegexValidator();
  11. }
  12. public function testNullIsValid()
  13. {
  14. $this->assertTrue($this->validator->isValid(null, new Regex(array('pattern' => '/^[0-9]+$/'))));
  15. }
  16. public function testEmptyStringIsValid()
  17. {
  18. $this->assertTrue($this->validator->isValid('', new Regex(array('pattern' => '/^[0-9]+$/'))));
  19. }
  20. public function testExpectsStringCompatibleType()
  21. {
  22. $this->setExpectedException('Symfony\Component\Validator\Exception\UnexpectedTypeException');
  23. $this->validator->isValid(new \stdClass(), new Regex(array('pattern' => '/^[0-9]+$/')));
  24. }
  25. /**
  26. * @dataProvider getValidValues
  27. */
  28. public function testValidValues($value)
  29. {
  30. $constraint = new Regex(array('pattern' => '/^[0-9]+$/'));
  31. $this->assertTrue($this->validator->isValid($value, $constraint));
  32. }
  33. public function getValidValues()
  34. {
  35. return array(
  36. array(0),
  37. array('0'),
  38. array('090909'),
  39. array(90909),
  40. );
  41. }
  42. /**
  43. * @dataProvider getInvalidValues
  44. */
  45. public function testInvalidValues($value)
  46. {
  47. $constraint = new Regex(array('pattern' => '/^[0-9]+$/'));
  48. $this->assertFalse($this->validator->isValid($value, $constraint));
  49. }
  50. public function getInvalidValues()
  51. {
  52. return array(
  53. array('abcd'),
  54. array('090foo'),
  55. );
  56. }
  57. public function testMessageIsSet()
  58. {
  59. $constraint = new Regex(array(
  60. 'pattern' => '/^[0-9]+$/',
  61. 'message' => 'myMessage'
  62. ));
  63. $this->assertFalse($this->validator->isValid('foobar', $constraint));
  64. $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
  65. $this->assertEquals($this->validator->getMessageParameters(), array(
  66. '{{ value }}' => 'foobar',
  67. ));
  68. }
  69. }