Skip to content

Commit

Permalink
minor #3687 throwing syntax error when the matches regexp is not vali…
Browse files Browse the repository at this point in the history
…d (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
-------

a82e94d Add some tests
61672c4 throwing syntaxt error when the matches regexp is not valid
  • Loading branch information
fabpot committed Dec 27, 2022
2 parents f6ef36a + a82e94d commit 4a7c8b3
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
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

0 comments on commit 4a7c8b3

Please sign in to comment.