From c14571ba26edbe26606127fdf89cd9793a7488ab Mon Sep 17 00:00:00 2001 From: Daimona Eaytoy Date: Wed, 5 Sep 2018 16:20:13 +0200 Subject: [PATCH] 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 --- includes/libs/StringUtils.php | 20 ++++++++++++++++ .../phpunit/includes/libs/StringUtilsTest.php | 24 +++++++++++++++++++ 2 files changed, 44 insertions(+) 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 ] + ]; + } } -- 2.20.1