minor #3687 throwing syntax error when the matches regexp is not valid (WebMamba, fabpot)

This PR was merged into the 3.x branch.

Discussion
----------

throwing syntax error when the matches regexp is not valid

During the symfony live, Fabien talk about a PR he did on the Expression Language component (https://github.com/symfony/symfony/pull/45875/files). The goal was to throw a more readable error when using the matchs operator. This think need to be fix in twig to. So as promises, here is my PR !
This is my first contrib to symfony so any advice is welcome ! 😁

Commits
-------

a82e94d9 Add some tests
61672c43 throwing syntaxt error when the matches regexp is not valid
This commit is contained in:
Fabien Potencier
2022-12-27 12:34:09 +01:00
3 changed files with 29 additions and 1 deletions
+20
View File
@@ -1019,6 +1019,26 @@ function twig_compare($a, $b)
return $a <=> $b;
}
/**
* @param string $pattern
* @param string $subject
*
* @return int
*
* @throws RuntimeError When an invalid pattern is used
*/
function twig_matches(string $regexp, string $str)
{
set_error_handler(function ($t, $m) use ($regexp) {
throw new RuntimeError(sprintf('Regexp "%s" passed to "matches" is not valid', $regexp).substr($m, 12));
});
try {
return preg_match($regexp, $str);
} finally {
restore_error_handler();
}
}
/**
* Returns a trimmed string.
*
+1 -1
View File
@@ -18,7 +18,7 @@ class MatchesBinary extends AbstractBinary
public function compile(Compiler $compiler): void
{
$compiler
->raw('preg_match(')
->raw('twig_matches(')
->subcompile($this->getNode('right'))
->raw(', ')
->subcompile($this->getNode('left'))
@@ -0,0 +1,8 @@
--TEST--
Twig supports the "matches" operator with a great error message
--TEMPLATE--
{{ 'foo' matches '/o' }}
--DATA--
return []
--EXCEPTION--
Twig\Error\RuntimeError: Regexp "/o" passed to "matches" is not valid: No ending delimiter '/' found in "index.twig" at line 2