Skip to content

[TwigComponent] merge props from template with class props #1652

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 18, 2024
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
18 changes: 11 additions & 7 deletions src/TwigComponent/src/ComponentRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,25 +107,29 @@ private function preRender(MountedComponent $mounted, array $context = []): PreR
{
$component = $mounted->getComponent();
$metadata = $this->factory->metadataFor($mounted->getName());
$isAnonymous = $mounted->getComponent() instanceof AnonymousComponent;

$classProps = $isAnonymous ? [] : iterator_to_array($this->exposedVariables($component, $metadata->isPublicPropsExposed()));

// expose public properties and properties marked with ExposeInTemplate attribute
$props = iterator_to_array($this->exposedVariables($component, $metadata->isPublicPropsExposed()));
$props = array_merge($mounted->getInputProps(), $classProps);
$variables = array_merge(
// first so values can be overridden
$context,

// add the context in a separate variable to keep track
// of what is coming from outside the component
['__context' => $context],
// keep reference to old context
['outerScope' => $context],

// add the component as "this"
['this' => $component],

// add computed properties proxy
['computed' => new ComputedPropertiesProxy($component)],

$props,
// keep this line for BC break reasons
['__props' => $classProps],
// add attributes
[$metadata->getAttributesVar() => $mounted->getAttributes()],
$props,
['__props' => $props]
);
$event = new PreRenderEvent($mounted, $metadata, $variables);

Expand Down
33 changes: 32 additions & 1 deletion src/TwigComponent/src/Twig/PropsNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,21 @@ public function compile(Compiler $compiler): void
;

foreach ($this->getAttribute('names') as $name) {
$compiler
->write('if (isset($context[\'__props\'][\''.$name.'\'])) {')
->raw("\n")
->write('$componentClass = isset($context[\'this\']) ? get_debug_type($context[\'this\']) : "";')
->raw("\n")
->write('throw new \Twig\Error\RuntimeError(\'Cannot define prop "'.$name.'" in template "'.$this->getTemplateName().'". Property already defined in component class "\'.$componentClass.\'".\');')
->raw("\n")
->write('}')
->raw("\n")
;

$compiler
->write('$propsNames[] = \''.$name.'\';')
->write('$context[\'attributes\'] = $context[\'attributes\']->remove(\''.$name.'\');')
->write('if (!isset($context[\'__props\'][\''.$name.'\'])) {');
->write('if (!isset($context[\''.$name.'\'])) {');

if (!$this->hasNode($name)) {
$compiler
Expand Down Expand Up @@ -66,5 +77,25 @@ public function compile(Compiler $compiler): void
->write('}')
->write('}')
;

// overwrite the context value if a props with a similar name and a default value exist
if ($this->hasNode($name)) {
$compiler
->write('if (isset($context[\'__context\'][\''.$name.'\'])) {')
->raw("\n")
->write('$contextValue = $context[\'__context\'][\''.$name.'\'];')
->raw("\n")
->write('$propsValue = $context[\''.$name.'\'];')
->raw("\n")
->write('if ($contextValue === $propsValue) {')
->raw("\n")
->write('$context[\''.$name.'\'] = ')
->subcompile($this->getNode($name))
->raw(";\n")
->write('}')
->raw("\n")
->write('}')
;
}
}
}
11 changes: 11 additions & 0 deletions src/TwigComponent/tests/Fixtures/Component/Conflict.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace Symfony\UX\TwigComponent\Tests\Fixtures\Component;

use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent]
class Conflict
{
public string $name;
}
20 changes: 20 additions & 0 deletions src/TwigComponent/tests/Fixtures/Component/FlashMessage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\UX\TwigComponent\Tests\Fixtures\Component;

use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent]
class FlashMessage
{
public string $message = '';
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<twig:Conflict name='foo'/>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<twig:FlashMessage message='Congrats !' color='success' size='lg'/>
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{% props name %}

<p>{{ name }}</p>
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{% props size = 'md', color = 'success' %}

<div data-color='{{ color }}' data-size='{{ size }}'>
{{ message }}
</div>
18 changes: 18 additions & 0 deletions src/TwigComponent/tests/Integration/ComponentExtensionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\UX\TwigComponent\Tests\Fixtures\User;
use Twig\Environment;
use Twig\Error\RuntimeError;

/**
* @author Kevin Bond <[email protected]>
Expand Down Expand Up @@ -341,6 +342,23 @@ public function testRenderingHtmlSyntaxComponentWithNestedAttributes(): void
);
}

public function testComponentWithPropsFromTemplateAndClass(): void
{
$output = self::getContainer()->get(Environment::class)->render('component_with_props_from_template_and_class.html.twig');

$this->assertStringContainsString('data-color=\'success\'', $output);
$this->assertStringContainsString('data-size=\'lg\'', $output);
$this->assertStringContainsString('Congrats !', $output);
}

public function testComponentWithConflictBetweenPropsFromTemplateAndClass(): void
{
$this->expectException(RuntimeError::class);
$this->expectExceptionMessage('Cannot define prop "name" in template "components/Conflict.html.twig". Property already defined in component class "Symfony\UX\TwigComponent\Tests\Fixtures\Component\Conflict".');

self::getContainer()->get(Environment::class)->render('component_with_conflict_between_props_from_template_and_class.html.twig');
}

private function renderComponent(string $name, array $data = []): string
{
return self::getContainer()->get(Environment::class)->render('render_component.html.twig', [
Expand Down
Loading