Skip to content

Commit

Permalink
throwing syntaxt error when the matches regexp is not valid
Browse files Browse the repository at this point in the history
  • Loading branch information
WebMamba committed Apr 18, 2022
1 parent b4d6723 commit 88befbd
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
21 changes: 21 additions & 0 deletions src/Extension/CoreExtension.php
Expand Up @@ -306,6 +306,7 @@ public function getOperators(): array
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;
Expand Down Expand Up @@ -1015,6 +1016,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.
*
Expand Down
2 changes: 1 addition & 1 deletion src/Node/Expression/Binary/MatchesBinary.php
Expand Up @@ -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'))
Expand Down

0 comments on commit 88befbd

Please sign in to comment.