Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@
use Symfony\UX\LiveComponent\Util\LiveControllerAttributesCreator;
use Symfony\UX\LiveComponent\Util\RequestPropsExtractor;
use Symfony\UX\LiveComponent\Util\TwigAttributeHelperFactory;
use Symfony\UX\LiveComponent\Util\UrlFactory;
use Symfony\UX\TwigComponent\ComponentFactory;
use Symfony\UX\TwigComponent\ComponentRenderer;

Expand Down Expand Up @@ -142,7 +141,7 @@ function (ChildDefinition $definition, AsLiveComponent $attribute) {
->setArguments([
new Reference('ux.live_component.metadata_factory'),
new Reference('ux.live_component.component_hydrator'),
new Reference('ux.live_component.url_factory'),
new Reference('router'),
])
->addTag('kernel.event_subscriber')
;
Expand Down Expand Up @@ -213,9 +212,6 @@ function (ChildDefinition $definition, AsLiveComponent $attribute) {

$container->register('ux.live_component.attribute_helper_factory', TwigAttributeHelperFactory::class);

$container->register('ux.live_component.url_factory', UrlFactory::class)
->setArguments([new Reference('router')]);

$container->register('ux.live_component.live_controller_attributes_creator', LiveControllerAttributesCreator::class)
->setArguments([
new Reference('ux.live_component.metadata_factory'),
Expand Down
111 changes: 72 additions & 39 deletions src/LiveComponent/src/EventListener/LiveUrlSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\RouterInterface;
use Symfony\UX\LiveComponent\LiveComponentHydrator;
use Symfony\UX\LiveComponent\Metadata\LiveComponentMetadataFactory;
use Symfony\UX\LiveComponent\Util\UrlFactory;
use Symfony\UX\TwigComponent\MountedComponent;

/**
Expand All @@ -29,35 +30,28 @@ class LiveUrlSubscriber implements EventSubscriberInterface
public function __construct(
private LiveComponentMetadataFactory $metadataFactory,
private LiveComponentHydrator $liveComponentHydrator,
private UrlFactory $urlFactory,
private RouterInterface $router,
) {
}

public function onKernelResponse(ResponseEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}

$request = $event->getRequest();
if (!$request->attributes->has('_live_component')) {
if (!$event->isMainRequest()
|| !$event->getResponse()->isSuccessful()
|| !$request->attributes->has('_live_component')
|| !$request->attributes->has('_mounted_component')
|| !($previousLiveUrl = $request->headers->get(self::URL_HEADER))
) {
return;
}

if (!$request->attributes->has('_mounted_component')) {
return;
}
/** @var MountedComponent $mounted */
$mounted = $request->attributes->get('_mounted_component');

$newLiveUrl = null;
if ($previousLiveUrl = $request->headers->get(self::URL_HEADER)) {
$mounted = $request->attributes->get('_mounted_component');
$liveProps = $this->getLiveProps($mounted);
$newLiveUrl = $this->urlFactory->createFromPreviousAndProps($previousLiveUrl, $liveProps['path'], $liveProps['query']);
}
[$pathProps, $queryProps] = $this->extractUrlLiveProps($mounted);

if ($newLiveUrl) {
$event->getResponse()->headers->set(self::URL_HEADER, $newLiveUrl);
}
$event->getResponse()->headers->set(self::URL_HEADER, $this->generateNewLiveUrl($previousLiveUrl, $pathProps, $queryProps));
}

public static function getSubscribedEvents(): array
Expand All @@ -68,34 +62,73 @@ public static function getSubscribedEvents(): array
}

/**
* @return array{
* path: array<string, mixed>,
* query: array<string, mixed>
* }
* @return array{ array<string, mixed>, array<string, mixed> }
*/
private function getLiveProps(MountedComponent $mounted): array
private function extractUrlLiveProps(MountedComponent $mounted): array
{
$metadata = $this->metadataFactory->getMetadata($mounted->getName());
$pathProps = $queryProps = [];

$mountedMetadata = $this->metadataFactory->getMetadata($mounted->getName());

if ([] !== $urlMappings = $mountedMetadata->getAllUrlMappings($mounted->getComponent())) {
$dehydratedProps = $this->liveComponentHydrator->dehydrate($mounted->getComponent(), $mounted->getAttributes(), $mountedMetadata);
$props = $dehydratedProps->getProps();

foreach ($urlMappings as $name => $urlMapping) {
if (\array_key_exists($name, $props)) {
if ($urlMapping->mapPath) {
$pathProps[$urlMapping->as ?? $name] = $props[$name];
} else {
$queryProps[$urlMapping->as ?? $name] = $props[$name];
}
}
}
}

$dehydratedProps = $this->liveComponentHydrator->dehydrate(
$mounted->getComponent(),
$mounted->getAttributes(),
$metadata
);
return [$pathProps, $queryProps];
}

$values = $dehydratedProps->getProps();
private function generateNewLiveUrl(string $previousUrl, array $pathProps, array $queryProps): string
{
$previousUrlParsed = parse_url($previousUrl);
$newUrl = $previousUrlParsed['path'];
$newQueryString = $previousUrlParsed['query'] ?? '';

if ([] !== $pathProps) {
$context = $this->router->getContext();
try {
// Re-create a context for the URL rendering the current LiveComponent
$tmpContext = clone $context;
$tmpContext->setMethod('GET');
$this->router->setContext($tmpContext);

$routeMatched = $this->router->match($previousUrlParsed['path']);
$routeParams = [];
foreach ($routeMatched as $k => $v) {
if ('_route' === $k || '_controller' === $k) {
continue;
}
$routeParams[$k] = \array_key_exists($k, $pathProps) ? $pathProps[$k] : $v;
}

$newUrl = $this->router->generate($routeMatched['_route'], $routeParams);
} catch (ResourceNotFoundException) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I removed the MethodNotAllowedException since I forced the context to GET method

// reuse the previous URL path
} finally {
$this->router->setContext($context);
}
}

$urlLiveProps = [
'path' => [],
'query' => [],
];
if ([] !== $queryProps) {
$previousQueryString = [];

foreach ($metadata->getAllUrlMappings($mounted->getComponent()) as $name => $urlMapping) {
if (isset($values[$name]) && $urlMapping) {
$urlLiveProps[$urlMapping->mapPath ? 'path' : 'query'][$urlMapping->as ?? $name] = $values[$name];
if (isset($previousUrlParsed['query'])) {
parse_str($previousUrlParsed['query'], $previousQueryString);
}

$newQueryString = http_build_query([...$previousQueryString, ...$queryProps]);
}

return $urlLiveProps;
return $newUrl.($newQueryString ? '?'.$newQueryString : '');
}
}
3 changes: 2 additions & 1 deletion src/LiveComponent/src/Metadata/LiveComponentMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,10 @@ public function getOnlyPropsThatAcceptUpdatesFromParent(array $inputProps): arra
/**
* @return UrlMapping[]
*/
public function getAllUrlMappings(object $component): iterable
public function getAllUrlMappings(object $component): array
{
$urlMappings = [];

foreach ($this->getAllLivePropsMetadata($component) as $livePropMetadata) {
if ($livePropMetadata->urlMapping()) {
$urlMappings[$livePropMetadata->getName()] = $livePropMetadata->urlMapping();
Expand Down
108 changes: 0 additions & 108 deletions src/LiveComponent/src/Util/UrlFactory.php

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ public function modifyMaybeBoundProp(LiveProp $prop): LiveProp
#[LiveProp(writable: true, url: new UrlMapping(as: 'pathAlias', mapPath: true))]
public ?string $pathPropWithAlias = null;

#[LiveProp(writable: true, url: new UrlMapping(mapPath: true))]
public ?string $pathPropForAnotherController = 'foo';

public function modifyBoundPropWithCustomAlias(LiveProp $liveProp): LiveProp
{
if ($this->customAlias) {
Expand Down
6 changes: 4 additions & 2 deletions src/LiveComponent/tests/Fixtures/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,9 @@ protected function configureRoutes(RoutingConfigurator $routes): void
$routes->add('homepage', '/')->controller('kernel::index');
$routes->add('alternate_live_route', '/alt/{_live_component}/{_live_action}')->defaults(['_live_action' => 'get']);
$routes->add('localized_route', '/locale/{_locale}/{_live_component}/{_live_action}')->defaults(['_live_action' => 'get']);
$routes->add('route_with_prop', '/route_with_prop/{pathProp}')->methods(['GET']);
$routes->add('route_with_alias_prop', '/route_with_alias_prop/{pathAlias}');
$routes->add('route_with_prop', '/route_with_prop/{pathProp}')->methods(['GET'])->requirements(['pathProp' => '\w+']);
$routes->add('route_with_alias_prop', '/route_with_alias_prop/{pathAlias}')->requirements(['pathAlias' => '\w+']);
$routes->add('route_with_two_props', '/route_with_two_props/{pathProp}/{pathAlias}')->methods(['GET'])->requirements(['pathProp' => '\w+', 'pathAlias' => '\w+']);
$routes->add('route_with_two_path_params_but_one_prop', '/route_with_two_path_params_but_one_prop/{pathProp}/{id}')->methods(['GET'])->requirements(['pathProp' => '\w+', 'id' => '\d+']);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ public function testQueryStringMappingAttribute()
'pathPropWithAlias' => ['name' => 'pathAlias'],
'objectPropWithSerializerForHydration' => ['name' => 'objectPropWithSerializerForHydration'],
'propertyWithModifierAndAlias' => ['name' => 'alias_p'],
'pathPropForAnotherController' => ['name' => 'pathPropForAnotherController'],
];

$this->assertEquals($expected, $queryMapping);
Expand Down
Loading
Loading