Skip to content

Commit 9815f9f

Browse files
committed
[TwigComponent][LiveComponent] Seek only for live components in stack
1 parent 24338fb commit 9815f9f

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed

src/LiveComponent/src/EventListener/DataModelPropsSubscriber.php

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,11 @@
1313

1414
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
1515
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
16+
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
1617
use Symfony\UX\LiveComponent\Util\ModelBindingParser;
1718
use Symfony\UX\TwigComponent\ComponentStack;
1819
use Symfony\UX\TwigComponent\Event\PreMountEvent;
20+
use Symfony\UX\TwigComponent\MountedComponent;
1921

2022
/**
2123
* Parses the "data-model" key, which triggers extra props to be passed in.
@@ -54,8 +56,9 @@ public function onPreMount(PreMountEvent $event): void
5456
unset($data['dataModel']);
5557
$data['data-model'] = $dataModel;
5658

57-
// the parent is still listed as the "current" component at this point
58-
$parentMountedComponent = $this->componentStack->getCurrentComponent();
59+
// find the first parent of the component about to be rendered that is a Live Component
60+
// only those can have properties controlled via the data-model attribute
61+
$parentMountedComponent = $this->getCurrentLiveComponent($this->componentStack);
5962
if (null === $parentMountedComponent) {
6063
throw new \LogicException('You can only pass "data-model" when rendering a component when you\'re rendering inside of a parent component.');
6164
}
@@ -76,4 +79,20 @@ public static function getSubscribedEvents(): array
7679
PreMountEvent::class => 'onPreMount',
7780
];
7881
}
82+
83+
private function getCurrentLiveComponent(ComponentStack $componentStack): ?MountedComponent
84+
{
85+
foreach ($componentStack as $mountedComponent) {
86+
if ($this->isLiveComponent($mountedComponent->getComponent()::class)) {
87+
return $mountedComponent;
88+
}
89+
}
90+
91+
return null;
92+
}
93+
94+
private function isLiveComponent(string $classname): bool
95+
{
96+
return [] !== (new \ReflectionClass($classname))->getAttributes(AsLiveComponent::class);
97+
}
7998
}

src/TwigComponent/src/ComponentStack.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
*
1717
* @internal
1818
*/
19-
class ComponentStack
19+
class ComponentStack implements \IteratorAggregate
2020
{
2121
/**
2222
* @var MountedComponent[]
@@ -60,4 +60,12 @@ public function hasParentComponent(): bool
6060
{
6161
return (bool) $this->getParentComponent();
6262
}
63+
64+
/**
65+
* @return MountedComponent[]|\ArrayIterator
66+
*/
67+
public function getIterator(): \Traversable
68+
{
69+
return new \ArrayIterator(array_reverse($this->components));
70+
}
6371
}

0 commit comments

Comments
 (0)