Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

throwing syntax error when the matches regexp is not valid #3687

Merged
merged 2 commits into from Dec 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/Extension/CoreExtension.php
Expand Up @@ -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.
*
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
8 changes: 8 additions & 0 deletions tests/Fixtures/expressions/matches_error.test
@@ -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