mirror of
https://github.com/twigphp/Twig.git
synced 2026-09-13 02:46:29 +00:00
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 -------a82e94d9Add some tests61672c43throwing syntaxt error when the matches regexp is not valid
This commit is contained in:
@@ -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.
|
||||
*
|
||||
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user