1212namespace Symfony \UX \Turbo \Twig ;
1313
1414use Psr \Container \ContainerInterface ;
15+ use Symfony \Component \HttpFoundation \RequestStack ;
16+ use Symfony \Component \Mercure \Authorization ;
1517use Symfony \UX \Turbo \Bridge \Mercure \TopicSet ;
1618use Twig \Environment ;
1719use Twig \Extension \AbstractExtension ;
1820use Twig \TwigFunction ;
1921
2022/**
2123 * @author Kévin Dunglas <[email protected] > 24+ * @author Pierre Ambroise <[email protected] > 2225 */
2326final class TwigExtension extends AbstractExtension
2427{
2528 public function __construct (
2629 private ContainerInterface $ turboStreamListenRenderers ,
2730 private string $ default ,
31+ private ?Authorization $ authorization = null ,
32+ private ?RequestStack $ requestStack = null ,
2833 ) {
2934 }
3035
@@ -37,8 +42,9 @@ public function getFunctions(): array
3742
3843 /**
3944 * @param object|string|array<object|string> $topic
45+ * @param array<string, mixed> $options
4046 */
41- public function turboStreamListen (Environment $ env , $ topic , ?string $ transport = null ): string
47+ public function turboStreamListen (Environment $ env , $ topic , ?string $ transport = null , array $ options = [] ): string
4248 {
4349 $ transport ??= $ this ->default ;
4450
@@ -50,6 +56,24 @@ public function turboStreamListen(Environment $env, $topic, ?string $transport =
5056 $ topic = new TopicSet ($ topic );
5157 }
5258
53- return $ this ->turboStreamListenRenderers ->get ($ transport )->renderTurboStreamListen ($ env , $ topic );
59+ if (
60+ null !== $ this ->authorization
61+ && null !== $ this ->requestStack
62+ && (isset ($ options ['subscribe ' ]) || isset ($ options ['publish ' ]) || isset ($ options ['additionalClaims ' ]))
63+ // @phpstan-ignore-next-line
64+ && null !== $ request = method_exists ($ this ->requestStack , 'getMainRequest ' ) ? $ this ->requestStack ->getMainRequest () : $ this ->requestStack ->getMasterRequest ()
65+ ) {
66+ $ this ->authorization ->setCookie (
67+ $ request ,
68+ $ options ['subscribe ' ] ?? [],
69+ $ options ['publish ' ] ?? [],
70+ $ options ['additionalClaims ' ] ?? [],
71+ $ transport ,
72+ );
73+
74+ unset($ options ['subscribe ' ], $ options ['publish ' ], $ options ['additionalClaims ' ]);
75+ }
76+
77+ return $ this ->turboStreamListenRenderers ->get ($ transport )->renderTurboStreamListen ($ env , $ topic , $ options );
5478 }
5579}
0 commit comments