From: Daimona Eaytoy Date: Wed, 5 Sep 2018 14:20:13 +0000 (+0200) Subject: StringUtils: Add a utility for checking if a string is a valid regex X-Git-Tag: 1.34.0-rc.0~159^2 X-Git-Url: http://git.cyclocoop.org/?a=commitdiff_plain;h=c14571ba26e;hp=2083ba21997bc214c34a5a1edbeef61b0cb98981;p=lhc%2Fweb%2Fwiklou.git StringUtils: Add a utility for checking if a string is a valid regex There's no function to check if a string is a valid regex, and doing it via preg_match requires error suppression, often performed with @. This isn't however a good practice, and suppressing errors via functions is not a one line solution. Adding an utility function would probably be a benefit for several use cases (try to grep '@preg_match' for a few of them). Change-Id: I257a096319f1ec13441e9f745dcd22545fdd5cc6 --- diff --git a/includes/libs/StringUtils.php b/includes/libs/StringUtils.php index 51d108168a..19dd8fe4d3 100644 --- a/includes/libs/StringUtils.php +++ b/includes/libs/StringUtils.php @@ -1,4 +1,7 @@ [ $PASS, "\xef\xbf\xbf" ], ]; } + + /** + * @param strin $input + * @param bool $expected + * @dataProvider provideRegexps + * @covers StringUtils::isValidRegex + */ + public function testIsValidRegex( $input, $expected ) { + $this->assertSame( $expected, StringUtils::isValidRegex( $input ) ); + } + + /** + * Data provider for testValidRegex + */ + public static function provideRegexps() { + return [ + [ 'foo', false ], + [ '/foo/', true ], + [ '//', true ], + [ '/(foo/', false ], + [ '!(f[o]{2})!', true ], + [ '/foo\/', false ] + ]; + } }