From 88befbd8839d1e4743d1cfe670e395ac5c6d7590 Mon Sep 17 00:00:00 2001 From: Matheo Daninos Date: Mon, 18 Apr 2022 22:03:37 +0200 Subject: [PATCH] throwing syntaxt error when the matches regexp is not valid --- src/Extension/CoreExtension.php | 21 ++++++++++++++++++++ src/Node/Expression/Binary/MatchesBinary.php | 2 +- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/Extension/CoreExtension.php b/src/Extension/CoreExtension.php index b779858598..0c0d8db33c 100644 --- a/src/Extension/CoreExtension.php +++ b/src/Extension/CoreExtension.php @@ -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; @@ -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. * diff --git a/src/Node/Expression/Binary/MatchesBinary.php b/src/Node/Expression/Binary/MatchesBinary.php index bc97292cda..a8bce6f4e7 100644 --- a/src/Node/Expression/Binary/MatchesBinary.php +++ b/src/Node/Expression/Binary/MatchesBinary.php @@ -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'))