Skip to content

Commit a4d63e0

Browse files
committed
Add ability to test regex errors
1 parent dd00bd5 commit a4d63e0

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

tests/Fixtures/preg-last-error.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php
2+
3+
/*
4+
* (c) Antal Áron <antalaron@antalaron.hu>
5+
*
6+
* For the full copyright and license information, please view the LICENSE
7+
* file that was distributed with this source code.
8+
*/
9+
10+
namespace Antalaron\RegexValidator;
11+
12+
final class ValidatorMock
13+
{
14+
public static $pregLastErrorMock = true;
15+
public static $pregLastError = \PREG_NO_ERROR;
16+
17+
private function __construct()
18+
{
19+
}
20+
}
21+
22+
function preg_last_error()
23+
{
24+
if (false === ValidatorMock::$pregLastErrorMock) {
25+
return \preg_last_error();
26+
}
27+
28+
return ValidatorMock::$pregLastError;
29+
}

tests/Tests/RegexValidatorTest.php

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,21 @@
99

1010
namespace Antalaron\RegexValidator\Tests;
1111

12+
require __DIR__.'/../Fixtures/preg-last-error.php';
13+
1214
use Antalaron\RegexValidator\Regex;
1315
use Antalaron\RegexValidator\RegexValidator;
16+
use Antalaron\RegexValidator\ValidatorMock;
1417

1518
class RegexValidatorTest extends AbstractConstraintValidatorTest
1619
{
20+
public function setUp()
21+
{
22+
parent::setUp();
23+
24+
ValidatorMock::$pregLastErrorMock = false;
25+
}
26+
1727
protected function createValidator()
1828
{
1929
return new RegexValidator();
@@ -49,4 +59,34 @@ public function regexProvider()
4959
['/abc', false, Regex::OTHER_ERROR],
5060
];
5161
}
62+
63+
/**
64+
* @dataProvider regexErrorProvider
65+
*/
66+
public function testRegexErrors($regex, $errorCode, $code)
67+
{
68+
ValidatorMock::$pregLastErrorMock = true;
69+
ValidatorMock::$pregLastError = $errorCode;
70+
71+
$this->validator->validate($regex, new Regex());
72+
73+
$this->assertSame(ValidatorMock::$pregLastErrorMock, true);
74+
75+
$this->buildViolation(Regex::MESSAGE)
76+
->setCode($code)
77+
->assertRaised();
78+
}
79+
80+
public function regexErrorProvider()
81+
{
82+
return [
83+
['/abc', \PREG_NO_ERROR, Regex::OTHER_ERROR],
84+
['/abc', \PREG_INTERNAL_ERROR, Regex::INTERNAL_ERROR],
85+
['/abc', \PREG_BACKTRACK_LIMIT_ERROR, Regex::BACKTRACK_LIMIT_ERROR],
86+
['/abc', \PREG_RECURSION_LIMIT_ERROR, Regex::RECURSION_LIMIT_ERROR],
87+
['/abc', \PREG_BAD_UTF8_ERROR, Regex::BAD_UTF8_ERROR],
88+
['/abc', \PREG_BAD_UTF8_OFFSET_ERROR, Regex::BAD_UTF8_OFFSET_ERROR],
89+
['/abc', defined('PREG_JIT_STACKLIMIT_ERROR') ? \PREG_JIT_STACKLIMIT_ERROR : \PREG_NO_ERROR, defined('PREG_JIT_STACKLIMIT_ERROR') ? Regex::JIT_STACKLIMIT_ERROR : Regex::OTHER_ERROR],
90+
];
91+
}
5292
}

0 commit comments

Comments
 (0)