4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Constraints;
14 use PHPUnit\Framework\TestCase;
15 use Symfony\Component\Validator\Constraints\Regex;
18 * @author Bernhard Schussek <bschussek@gmail.com>
20 class RegexTest extends TestCase
22 public function testConstraintGetDefaultOption()
24 $constraint = new Regex('/^[0-9]+$/');
26 $this->assertSame('/^[0-9]+$/', $constraint->pattern);
29 public function provideHtmlPatterns()
32 // HTML5 wraps the pattern in ^(?:pattern)$
33 array('/^[0-9]+$/', '[0-9]+'),
34 array('/[0-9]+$/', '.*[0-9]+'),
35 array('/^[0-9]+/', '[0-9]+.*'),
36 array('/[0-9]+/', '.*[0-9]+.*'),
37 // We need a smart way to allow matching of patterns that contain
38 // ^ and $ at various sub-clauses of an or-clause
39 // .*(pattern).* seems to work correctly
40 array('/[0-9]$|[a-z]+/', '.*([0-9]$|[a-z]+).*'),
41 array('/[0-9]$|^[a-z]+/', '.*([0-9]$|^[a-z]+).*'),
42 array('/^[0-9]|[a-z]+$/', '.*(^[0-9]|[a-z]+$).*'),
43 // Unescape escaped delimiters
44 array('/^[0-9]+\/$/', '[0-9]+/'),
45 array('#^[0-9]+\#$#', '[0-9]+#'),
46 // Cannot be converted
47 array('/^[0-9]+$/i', null),
49 // Inverse matches are simple, just wrap in
51 array('/^[0-9]+$/', '((?!^[0-9]+$).)*', false),
52 array('/[0-9]+$/', '((?![0-9]+$).)*', false),
53 array('/^[0-9]+/', '((?!^[0-9]+).)*', false),
54 array('/[0-9]+/', '((?![0-9]+).)*', false),
55 array('/[0-9]$|[a-z]+/', '((?![0-9]$|[a-z]+).)*', false),
56 array('/[0-9]$|^[a-z]+/', '((?![0-9]$|^[a-z]+).)*', false),
57 array('/^[0-9]|[a-z]+$/', '((?!^[0-9]|[a-z]+$).)*', false),
58 array('/^[0-9]+\/$/', '((?!^[0-9]+/$).)*', false),
59 array('#^[0-9]+\#$#', '((?!^[0-9]+#$).)*', false),
60 array('/^[0-9]+$/i', null, false),
65 * @dataProvider provideHtmlPatterns
67 public function testGetHtmlPattern($pattern, $htmlPattern, $match = true)
69 $constraint = new Regex(array(
70 'pattern' => $pattern,
74 $this->assertSame($pattern, $constraint->pattern);
75 $this->assertSame($htmlPattern, $constraint->getHtmlPattern());
78 public function testGetCustomHtmlPattern()
80 $constraint = new Regex(array(
81 'pattern' => '((?![0-9]$|[a-z]+).)*',
82 'htmlPattern' => 'foobar',
85 $this->assertSame('((?![0-9]$|[a-z]+).)*', $constraint->pattern);
86 $this->assertSame('foobar', $constraint->getHtmlPattern());