Skip to content

Commit 03504fc

Browse files
author
matheo
committed
destruct option to ExposeInTemplate attribute
1 parent 1d55891 commit 03504fc

File tree

3 files changed

+17
-9
lines changed

3 files changed

+17
-9
lines changed

src/TwigComponent/src/AnonymousComponent.php

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,27 +11,25 @@
1111

1212
namespace Symfony\UX\TwigComponent;
1313

14+
use Symfony\UX\TwigComponent\Attribute\ExposeInTemplate;
15+
1416
/**
1517
* @author Matheo Daninos <[email protected]>
1618
*
1719
* @internal
1820
*/
1921
class AnonymousComponent
2022
{
21-
private array $props = [];
23+
private array $props;
2224

23-
public function setProps(array $props)
25+
public function mount($props = []): void
2426
{
2527
$this->props = $props;
2628
}
2729

30+
#[ExposeInTemplate(destruct: true)]
2831
public function getProps(): array
2932
{
3033
return $this->props;
3134
}
32-
33-
public function mount(array $props = [])
34-
{
35-
$this->setProps($props);
36-
}
3735
}

src/TwigComponent/src/Attribute/ExposeInTemplate.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,10 @@ final class ExposeInTemplate
2626
* to default to property name.
2727
* @param string|null $getter The getter method to use. Leave as null
2828
* to default to PropertyAccessor logic.
29+
* @param bool $destruct The content should be used as array of variables
30+
* names
2931
*/
30-
public function __construct(public ?string $name = null, public ?string $getter = null)
32+
public function __construct(public ?string $name = null, public ?string $getter = null, public bool $destruct = false)
3133
{
3234
}
3335
}

src/TwigComponent/src/ComponentRenderer.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,6 @@ private function preRender(MountedComponent $mounted, array $context = []): PreR
105105

106106
// expose public properties and properties marked with ExposeInTemplate attribute
107107
iterator_to_array($this->exposedVariables($component, $metadata->isPublicPropsExposed())),
108-
$component instanceof AnonymousComponent ? $component->getProps() : []
109108
);
110109
$event = new PreRenderEvent($mounted, $metadata, $variables);
111110

@@ -149,6 +148,15 @@ private function exposedVariables(object $component, bool $exposePublicProps): \
149148
throw new \LogicException(sprintf('Cannot use %s on methods with required parameters (%s::%s).', ExposeInTemplate::class, $component::class, $method->name));
150149
}
151150

151+
152+
if ($attribute->destruct) {
153+
foreach ($component->{$method->name}() as $prop => $value) {
154+
yield $prop => $value;
155+
}
156+
157+
return;
158+
}
159+
152160
yield $name => $component->{$method->name}();
153161
}
154162
}

0 commit comments

Comments
 (0)