From 368fbdbd87f290626c29b0f9a3a64db75c50f1ae Mon Sep 17 00:00:00 2001 From: Simon Vieille Date: Thu, 25 Mar 2021 14:32:51 +0100 Subject: [PATCH] add twig function to use path safetly --- core/Twig/Extension/RoutingExtension.php | 28 ++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/core/Twig/Extension/RoutingExtension.php b/core/Twig/Extension/RoutingExtension.php index e57043e..287ea93 100644 --- a/core/Twig/Extension/RoutingExtension.php +++ b/core/Twig/Extension/RoutingExtension.php @@ -29,9 +29,37 @@ class RoutingExtension extends AbstractExtension new TwigFunction('node_path', [$this, 'getNodePath'], ['is_safe_callback' => [$this, 'isUrlGenerationSafe']]), new TwigFunction('safe_node_url', [$this, 'getSafeNodeUrl'], ['is_safe_callback' => [$this, 'isUrlGenerationSafe']]), new TwigFunction('safe_node_path', [$this, 'getSafeNodePath'], ['is_safe_callback' => [$this, 'isUrlGenerationSafe']]), + new TwigFunction('safe_url', [$this, 'getSafeUrl'], ['is_safe_callback' => [$this, 'isUrlGenerationSafe']]), + new TwigFunction('safe_path', [$this, 'getSafePath'], ['is_safe_callback' => [$this, 'isUrlGenerationSafe']]), ]; } + public function getSafePath(string $route, array $parameters = [], bool $relative = false): ?string + { + try { + return $this->generator->generate( + $route, + $parameters, + $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH + ); + } catch (\Exception $e) { + return null; + } + } + + public function getSafeUrl(string $route, array $parameters = [], bool $schemeRelative = false): ?string + { + try { + return $this->generator->generate( + $route, + $parameters, + $schemeRelative ? UrlGeneratorInterface::NETWORK_PATH : UrlGeneratorInterface::ABSOLUTE_URL + ); + } catch (\Exception $e) { + return null; + } + } + public function getNodePath(Node $node, array $parameters = [], bool $relative = false): ?string { if ($node->hasExternalUrl()) {