4
4
5
5
use Psr \Container \ContainerInterface ;
6
6
use Symfony \Component \EventDispatcher \EventSubscriberInterface ;
7
+ use Symfony \Component \Routing \Generator \UrlGeneratorInterface ;
8
+ use Symfony \Component \Security \Csrf \CsrfTokenManagerInterface ;
7
9
use Symfony \Contracts \Service \ServiceSubscriberInterface ;
8
- use Symfony \UX \LiveComponent \Twig \ LiveComponentRuntime ;
10
+ use Symfony \UX \LiveComponent \LiveComponentHydrator ;
9
11
use Symfony \UX \TwigComponent \ComponentAttributes ;
12
+ use Symfony \UX \TwigComponent \ComponentMetadata ;
10
13
use Symfony \UX \TwigComponent \EventListener \PreRenderEvent ;
14
+ use Twig \Environment ;
11
15
12
16
/**
13
17
* @author Kevin Bond <[email protected] >
@@ -25,11 +29,7 @@ public function onPreRender(PreRenderEvent $event): void
25
29
return ;
26
30
}
27
31
28
- /** @var ComponentAttributes $attributes */
29
- $ attributes = $ this ->container ->get (LiveComponentRuntime::class)
30
- ->getLiveAttributes ($ event ->getComponent (), $ event ->getMetadata ())
31
- ;
32
-
32
+ $ attributes = $ this ->getLiveAttributes ($ event ->getComponent (), $ event ->getMetadata ());
33
33
$ variables = $ event ->getVariables ();
34
34
35
35
if (isset ($ variables ['attributes ' ]) && $ variables ['attributes ' ] instanceof ComponentAttributes) {
@@ -50,7 +50,33 @@ public static function getSubscribedEvents(): array
50
50
public static function getSubscribedServices (): array
51
51
{
52
52
return [
53
- LiveComponentRuntime::class,
53
+ LiveComponentHydrator::class,
54
+ UrlGeneratorInterface::class,
55
+ Environment::class,
56
+ '? ' .CsrfTokenManagerInterface::class,
54
57
];
55
58
}
59
+
60
+ private function getLiveAttributes (object $ component , ComponentMetadata $ metadata ): ComponentAttributes
61
+ {
62
+ $ url = $ this ->container ->get (UrlGeneratorInterface::class)
63
+ ->generate ('live_component ' , ['component ' => $ metadata ->getName ()])
64
+ ;
65
+ $ data = $ this ->container ->get (LiveComponentHydrator::class)->dehydrate ($ component );
66
+ $ twig = $ this ->container ->get (Environment::class);
67
+
68
+ $ attributes = [
69
+ 'data-controller ' => 'live ' ,
70
+ 'data-live-url-value ' => twig_escape_filter ($ twig , $ url , 'html_attr ' ),
71
+ 'data-live-data-value ' => twig_escape_filter ($ twig , json_encode ($ data , \JSON_THROW_ON_ERROR ), 'html_attr ' ),
72
+ ];
73
+
74
+ if ($ this ->container ->has (CsrfTokenManagerInterface::class)) {
75
+ $ attributes ['data-live-csrf-value ' ] = $ this ->container ->get (CsrfTokenManagerInterface::class)
76
+ ->getToken ($ metadata ->getName ())->getValue ()
77
+ ;
78
+ }
79
+
80
+ return new ComponentAttributes ($ attributes );
81
+ }
56
82
}
0 commit comments