12
12
namespace Symfony \UX \Turbo \Twig ;
13
13
14
14
use Psr \Container \ContainerInterface ;
15
+ use Symfony \Component \HttpFoundation \RequestStack ;
16
+ use Symfony \Component \Mercure \Authorization ;
15
17
use Symfony \UX \Turbo \Bridge \Mercure \TopicSet ;
16
18
use Twig \Environment ;
17
19
use Twig \Extension \AbstractExtension ;
18
20
use Twig \TwigFunction ;
19
21
20
22
/**
21
23
* @author Kévin Dunglas <kevin@dunglas.fr>
24
+ * @author Pierre Ambroise <pierre27.ambroise@gmail.com>
22
25
*/
23
26
final class TwigExtension extends AbstractExtension
24
27
{
25
28
public function __construct (
26
29
private ContainerInterface $ turboStreamListenRenderers ,
27
30
private string $ default ,
31
+ private ?Authorization $ authorization = null ,
32
+ private ?RequestStack $ requestStack = null ,
28
33
) {
29
34
}
30
35
@@ -37,8 +42,9 @@ public function getFunctions(): array
37
42
38
43
/**
39
44
* @param object|string|array<object|string> $topic
45
+ * @param array<string, mixed> $options
40
46
*/
41
- public function turboStreamListen (Environment $ env , $ topic , ?string $ transport = null ): string
47
+ public function turboStreamListen (Environment $ env , $ topic , ?string $ transport = null , array $ options = [] ): string
42
48
{
43
49
$ transport ??= $ this ->default ;
44
50
@@ -50,6 +56,24 @@ public function turboStreamListen(Environment $env, $topic, ?string $transport =
50
56
$ topic = new TopicSet ($ topic );
51
57
}
52
58
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 );
54
78
}
55
79
}
0 commit comments