1414use Symfony \Component \ErrorHandler \ErrorRenderer \ErrorRendererInterface ;
1515use Symfony \Component \ErrorHandler \ErrorRenderer \HtmlErrorRenderer ;
1616use Symfony \Component \ErrorHandler \Exception \FlattenException ;
17+ use Symfony \Component \HttpFoundation \RequestStack ;
1718use Twig \Environment ;
1819use Twig \Error \LoaderError ;
1920use Twig \Loader \ExistsLoaderInterface ;
@@ -30,8 +31,15 @@ class TwigErrorRenderer implements ErrorRendererInterface
3031 private $ fallbackErrorRenderer ;
3132 private $ debug ;
3233
33- public function __construct (Environment $ twig , HtmlErrorRenderer $ fallbackErrorRenderer = null , bool $ debug = false )
34+ /**
35+ * @param bool|callable $debug The debugging mode as a boolean or a callable that should return it
36+ */
37+ public function __construct (Environment $ twig , HtmlErrorRenderer $ fallbackErrorRenderer = null , $ debug = false )
3438 {
39+ if (!\is_bool ($ debug ) && !\is_callable ($ debug )) {
40+ throw new \TypeError (sprintf ('Argument 2 passed to %s() must be a boolean or a callable, %s given. ' , __METHOD__ , \is_object ($ debug ) ? \get_class ($ debug ) : \gettype ($ debug )));
41+ }
42+
3543 $ this ->twig = $ twig ;
3644 $ this ->fallbackErrorRenderer = $ fallbackErrorRenderer ?? new HtmlErrorRenderer ();
3745 $ this ->debug = $ debug ;
@@ -43,8 +51,9 @@ public function __construct(Environment $twig, HtmlErrorRenderer $fallbackErrorR
4351 public function render (\Throwable $ exception ): FlattenException
4452 {
4553 $ exception = $ this ->fallbackErrorRenderer ->render ($ exception );
54+ $ debug = \is_bool ($ this ->debug ) ? $ this ->debug : ($ this ->debug )($ exception );
4655
47- if ($ this -> debug || !$ template = $ this ->findTemplate ($ exception ->getStatusCode ())) {
56+ if ($ debug || !$ template = $ this ->findTemplate ($ exception ->getStatusCode ())) {
4857 return $ exception ;
4958 }
5059
@@ -56,6 +65,17 @@ public function render(\Throwable $exception): FlattenException
5665 ]));
5766 }
5867
68+ public static function isDebug (RequestStack $ requestStack , bool $ debug ): \Closure
69+ {
70+ return static function () use ($ requestStack , $ debug ): bool {
71+ if (!$ request = $ requestStack ->getCurrentRequest ()) {
72+ return $ debug ;
73+ }
74+
75+ return $ debug && $ request ->attributes ->getBoolean ('showException ' , true );
76+ };
77+ }
78+
5979 private function findTemplate (int $ statusCode ): ?string
6080 {
6181 $ template = sprintf ('@Twig/Exception/error%s.html.twig ' , $ statusCode );
0 commit comments