RegexValidatorTest.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Tests\Component\Validator\Constraints;
  11. use Symfony\Component\Validator\Constraints\Regex;
  12. use Symfony\Component\Validator\Constraints\RegexValidator;
  13. class RegexValidatorTest extends \PHPUnit_Framework_TestCase
  14. {
  15. protected $validator;
  16. protected function setUp()
  17. {
  18. $this->validator = new RegexValidator();
  19. }
  20. public function testNullIsValid()
  21. {
  22. $this->assertTrue($this->validator->isValid(null, new Regex(array('pattern' => '/^[0-9]+$/'))));
  23. }
  24. public function testEmptyStringIsValid()
  25. {
  26. $this->assertTrue($this->validator->isValid('', new Regex(array('pattern' => '/^[0-9]+$/'))));
  27. }
  28. public function testExpectsStringCompatibleType()
  29. {
  30. $this->setExpectedException('Symfony\Component\Validator\Exception\UnexpectedTypeException');
  31. $this->validator->isValid(new \stdClass(), new Regex(array('pattern' => '/^[0-9]+$/')));
  32. }
  33. /**
  34. * @dataProvider getValidValues
  35. */
  36. public function testValidValues($value)
  37. {
  38. $constraint = new Regex(array('pattern' => '/^[0-9]+$/'));
  39. $this->assertTrue($this->validator->isValid($value, $constraint));
  40. }
  41. public function getValidValues()
  42. {
  43. return array(
  44. array(0),
  45. array('0'),
  46. array('090909'),
  47. array(90909),
  48. );
  49. }
  50. /**
  51. * @dataProvider getInvalidValues
  52. */
  53. public function testInvalidValues($value)
  54. {
  55. $constraint = new Regex(array('pattern' => '/^[0-9]+$/'));
  56. $this->assertFalse($this->validator->isValid($value, $constraint));
  57. }
  58. public function getInvalidValues()
  59. {
  60. return array(
  61. array('abcd'),
  62. array('090foo'),
  63. );
  64. }
  65. public function testMessageIsSet()
  66. {
  67. $constraint = new Regex(array(
  68. 'pattern' => '/^[0-9]+$/',
  69. 'message' => 'myMessage'
  70. ));
  71. $this->assertFalse($this->validator->isValid('foobar', $constraint));
  72. $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
  73. $this->assertEquals($this->validator->getMessageParameters(), array(
  74. '{{ value }}' => 'foobar',
  75. ));
  76. }
  77. }