throwing syntaxt error when the matches regexp is not valid

This commit is contained in:
Matheo Daninos
2022-04-18 22:03:37 +02:00
committed by Fabien Potencier
parent f6ef36a447
commit 61672c43f9
2 changed files with 22 additions and 1 deletions
+21
View File
@@ -310,6 +310,7 @@ namespace {
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
use Twig\Extension\CoreExtension;
use Twig\Extension\SandboxExtension;
use Twig\Markup;
@@ -1019,6 +1020,26 @@ function twig_compare($a, $b)
return $a <=> $b;
}
/**
* @param string $pattern
* @param string $subject
*
* @return int
*
* @throws SyntaxError When an invalid pattern is used
*/
function twig_matches(string $regexp, string $str)
{
set_error_handler(function ($t, $m) use ($regexp) {
throw new SyntaxError(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'))