44
55use Psr \Container \ContainerInterface ;
66use Symfony \Component \EventDispatcher \EventSubscriberInterface ;
7+ use Symfony \Component \Routing \Generator \UrlGeneratorInterface ;
8+ use Symfony \Component \Security \Csrf \CsrfTokenManagerInterface ;
79use Symfony \Contracts \Service \ServiceSubscriberInterface ;
8- use Symfony \UX \LiveComponent \Twig \ LiveComponentRuntime ;
10+ use Symfony \UX \LiveComponent \LiveComponentHydrator ;
911use Symfony \UX \TwigComponent \ComponentAttributes ;
12+ use Symfony \UX \TwigComponent \ComponentMetadata ;
1013use Symfony \UX \TwigComponent \EventListener \PreRenderEvent ;
14+ use Twig \Environment ;
1115
1216/**
1317 * @author Kevin Bond <[email protected] > @@ -25,11 +29,7 @@ public function onPreRender(PreRenderEvent $event): void
2529 return ;
2630 }
2731
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 ());
3333 $ variables = $ event ->getVariables ();
3434
3535 if (isset ($ variables ['attributes ' ]) && $ variables ['attributes ' ] instanceof ComponentAttributes) {
@@ -50,7 +50,33 @@ public static function getSubscribedEvents(): array
5050 public static function getSubscribedServices (): array
5151 {
5252 return [
53- LiveComponentRuntime::class,
53+ LiveComponentHydrator::class,
54+ UrlGeneratorInterface::class,
55+ Environment::class,
56+ '? ' .CsrfTokenManagerInterface::class,
5457 ];
5558 }
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+ }
5682}
0 commit comments