Skip to content

Commit 98a4acc

Browse files
committed
Add Hierarchy proxy to be able to access properties of parent of parent (unlimited) inside embedded components
1 parent 14115f1 commit 98a4acc

10 files changed

+250
-14
lines changed

src/TwigComponent/src/ComponentRenderer.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,13 +115,21 @@ private function preRender(MountedComponent $mounted, array $context = []): PreR
115115
}
116116

117117
$component = $mounted->getComponent();
118+
119+
// add the "parent" component when rendering a nested embedded component
120+
if (isset($context[PreRenderEvent::EMBEDDED]) && true === $context[PreRenderEvent::EMBEDDED]) {
121+
$hierarchy = isset($context['this']) && $context['this'] instanceof Hierarchy ? $context['this'] : new Hierarchy($component);
122+
if (isset($context['this'])) {
123+
$hierarchy = $hierarchy->add($component);
124+
}
125+
}
118126
$metadata = $this->factory->metadataFor($mounted->getName());
119127
$variables = array_merge(
120128
// first so values can be overridden
121129
$context,
122130

123131
// add the component as "this"
124-
['this' => $component],
132+
['this' => $hierarchy ?? $component],
125133

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

src/TwigComponent/src/Hierarchy.php

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Symfony\UX\TwigComponent;
6+
7+
final class Hierarchy
8+
{
9+
public function __construct(private object $component, public ?self $parent = null)
10+
{
11+
}
12+
13+
public function add(object $component): self
14+
{
15+
return new self($component, $this);
16+
}
17+
18+
public function __call(string $name, array $arguments): mixed
19+
{
20+
if (isset($this->component->$name)) {
21+
// try property
22+
return $this->component->$name;
23+
}
24+
25+
if ($this->component instanceof \ArrayAccess && isset($this->component[$name])) {
26+
return $this->component[$name];
27+
}
28+
29+
$method = $this->normalizeMethod($name);
30+
31+
return $this->component->$method(...$arguments);
32+
}
33+
34+
private function normalizeMethod(string $name): string
35+
{
36+
if (method_exists($this->component, $name)) {
37+
return $name;
38+
}
39+
40+
foreach (['get', 'is', 'has'] as $prefix) {
41+
if (method_exists($this->component, $method = sprintf('%s%s', $prefix, ucfirst($name)))) {
42+
return $method;
43+
}
44+
}
45+
46+
throw new \InvalidArgumentException(sprintf('Component "%s" does not have a "%s" method.', $this->component::class, $name));
47+
}
48+
}

src/TwigComponent/tests/Fixtures/Component/DivComponentWrapper.php

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,4 @@
1919
#[AsTwigComponent]
2020
final class DivComponentWrapper
2121
{
22-
public string $divComponentWrapperName = 'bar';
23-
24-
public function someFunction(): string
25-
{
26-
return 'calling DivComponentWrapper';
27-
}
2822
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\UX\TwigComponent\Tests\Fixtures\Component;
13+
14+
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;
15+
16+
/**
17+
* @author Bart Vanderstukken <[email protected]>
18+
*/
19+
#[AsTwigComponent]
20+
final class DivComponentWrapper3
21+
{
22+
public string $divComponentWrapperName = 'bar';
23+
24+
public function someFunction(): string
25+
{
26+
return 'calling DivComponentWrapper';
27+
}
28+
}

src/TwigComponent/tests/Fixtures/templates/components/DivComponent5.html.twig

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
I can access my own properties: {{ divComponentName }}.
33
I can access the id of the Generic Element: {{ id }}.
44
This refers to the Generic Element: {{ this.someFunction }}.
5+
To access my own functions I can use this.parent: {{ this.parent.someFunction }}.
56
I have access to outer context variables like {{ name }}.
67
{{ block(outerBlocks.content) }}
78
</twig:GenericElement>
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<twig:DivComponent5>
2+
I can access the id from Generic Element as well: {{ id }}.
3+
I can access the properties from DivComponent as well: {{ divComponentName }}.
4+
And of course the properties from DivComponentWrapper: {{ divComponentWrapperName }}.
5+
The less obvious thing is that at this level "this" refers to the component where the content block is used, i.e. the Generic Element.
6+
Therefore, functions through this will be {{ this.someFunction }}.
7+
Calls to this.parent will be {{ this.parent.someFunction }}.
8+
{{ block(outerBlocks.content) }}
9+
</twig:DivComponent5>
Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
{% set name = 'Fabien' %}
2-
<twig:DivComponent5>
3-
I can access the id from Generic Element as well: {{ id }}.
4-
I can access the properties from DivComponent as well: {{ divComponentName }}.
5-
The less obvious thing is that at this level "this" refers to the component where the content block is used, i.e. the Generic Element.
6-
Therefore, functions through this will be {{ this.someFunction }}.
7-
</twig:DivComponent5>
2+
<twig:DivComponentWrapper3>
3+
Even I can access the id from Generic Element as well: {{ id }}.
4+
Even I can access the properties from DivComponent as well: {{ divComponentName }}.
5+
Even I can access the properties from DivComponentWrapper as well: {{ divComponentWrapperName }}.
6+
Even I can access the functions of DivComponent via this.parent: {{ this.parent.someFunction }}.
7+
Since we are nesting two levels deep, calls to this.parent.parent will be {{ this.parent.parent.someFunction }}.
8+
</twig:DivComponentWrapper3>
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
<twig:GenericElement element="div" class="divComponent">
2+
{{ this.parent.foo }}
3+
</twig:GenericElement>

src/TwigComponent/tests/Integration/EmbeddedComponentTest.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,15 +140,22 @@ public function testPassingDownBlocksMultipleLevelsNeedsToBeDoneManually(): void
140140

141141
/**
142142
* Rule 12: Blocks defined within an embedded component can access the context of the block they are replacing.
143+
* Rule 13: Blocks defined within an embedded component can access the context of components up the hierarchy (up to their own level) via "this.parent".
143144
*/
144145
public function testBlockDefinitionCanAccessTheContextOfTheDestinationBlocks(): void
145146
{
146147
$this->assertStringContainsStringIgnoringIndentation(
147-
'<div class="divComponent">I can access my own properties: foo.I can access the id of the Generic Element: symfonyIsAwesome.This refers to the Generic Element: calling GenericElement.I have access to outer context variables like Fabien.I can access the id from Generic Element as well: symfonyIsAwesome.I can access the properties from DivComponent as well: foo.The less obvious thing is that at this level "this" refers to the component where the content block is used, i.e. the Generic Element.Therefore, functions through this will be calling GenericElement.<span class="foo">The Generic Element default foo block</span></div>',
148+
'<div class="divComponent">I can access my own properties: foo.I can access the id of the Generic Element: symfonyIsAwesome.This refers to the Generic Element: calling GenericElement.To access my own functions I can use this.parent: calling DivComponent.I have access to outer context variables like Fabien.I can access the id from Generic Element as well: symfonyIsAwesome.I can access the properties from DivComponent as well: foo.And of course the properties from DivComponentWrapper: bar.The less obvious thing is that at this level "this" refers to the component where the content block is used, i.e. the Generic Element.Therefore, functions through this will be calling GenericElement.Calls to this.parent will be calling DivComponent.Even I can access the id from Generic Element as well: symfonyIsAwesome.Even I can access the properties from DivComponent as well: foo.Even I can access the properties from DivComponentWrapper as well: bar.Even I can access the functions of DivComponent via this.parent: calling DivComponent.Since we are nesting two levels deep, calls to this.parent.parent will be calling DivComponentWrapper.<span class="foo">The Generic Element default foo block</span></div>',
148149
self::getContainer()->get(Environment::class)->render('embedded_component_blocks_context.html.twig')
149150
);
150151
}
151152

153+
public function testAccessingTheHierarchyToHighThrowsAnException(): void
154+
{
155+
$this->expectExceptionMessage('Impossible to access an attribute ("foo") on a null variable');
156+
self::getContainer()->get(Environment::class)->render('embedded_component_hierarchy_exception.html.twig');
157+
}
158+
152159
public function testANonEmbeddedComponentRendersOuterBlocksEmpty(): void
153160
{
154161
$this->assertStringContainsStringIgnoringIndentation(
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
<?php
2+
3+
namespace Symfony\UX\TwigComponent\Tests\Unit;
4+
5+
use PHPUnit\Framework\TestCase;
6+
use Symfony\UX\TwigComponent\Hierarchy;
7+
8+
/**
9+
* @author Bart Vanderstukken <[email protected]>
10+
*/
11+
final class HierarchyTest extends TestCase
12+
{
13+
public function testCanProxyGetters(): void
14+
{
15+
$hierarchy = new Hierarchy(new class() {
16+
private int $count = 0;
17+
18+
public function getCount(): int
19+
{
20+
return ++$this->count;
21+
}
22+
});
23+
24+
$this->assertSame(1, $hierarchy->getCount());
25+
$this->assertSame(2, $hierarchy->count());
26+
}
27+
28+
public function testCanProxyIssers(): void
29+
{
30+
$hierarchy = new Hierarchy(new class() {
31+
private int $count = 0;
32+
33+
public function isCount(): int
34+
{
35+
return ++$this->count;
36+
}
37+
});
38+
39+
$this->assertSame(1, $hierarchy->isCount());
40+
$this->assertSame(2, $hierarchy->count());
41+
}
42+
43+
public function testCanProxyHassers(): void
44+
{
45+
$hierarchy = new Hierarchy(new class() {
46+
private int $count = 0;
47+
48+
public function hasCount(): int
49+
{
50+
return ++$this->count;
51+
}
52+
});
53+
54+
$this->assertSame(1, $hierarchy->hasCount());
55+
$this->assertSame(2, $hierarchy->count());
56+
}
57+
58+
public function testCanProxyGettersWithArguments(): void
59+
{
60+
$hierarchy = new Hierarchy(new class() {
61+
private int $count = 0;
62+
63+
public function getCount(int $step, int $jump = 0): int
64+
{
65+
return $this->count += $step + $jump;
66+
}
67+
});
68+
69+
$this->assertSame(5, $hierarchy->getCount(5));
70+
$this->assertSame(20, $hierarchy->count(5, 10));
71+
}
72+
73+
public function testCanProxyPublicProperties(): void
74+
{
75+
$hierarchy = new Hierarchy(new class() {
76+
public $foo = 'bar';
77+
});
78+
79+
$this->assertSame('bar', $hierarchy->foo());
80+
}
81+
82+
public function testCanProxyArrayAccess(): void
83+
{
84+
$hierarchy = new Hierarchy(new class() implements \ArrayAccess {
85+
private $array = ['foo' => 'bar'];
86+
87+
public function offsetExists(mixed $offset): bool
88+
{
89+
return isset($this->array[$offset]);
90+
}
91+
92+
public function offsetGet(mixed $offset): mixed
93+
{
94+
return $this->array[$offset];
95+
}
96+
97+
public function offsetSet(mixed $offset, mixed $value): void
98+
{
99+
}
100+
101+
public function offsetUnset(mixed $offset): void
102+
{
103+
}
104+
});
105+
106+
$this->assertSame('bar', $hierarchy->foo());
107+
}
108+
109+
public function testCannotProxyMethodsThatDoNotExist(): void
110+
{
111+
$hierarchy = new Hierarchy(new class() {});
112+
113+
$this->expectException(\InvalidArgumentException::class);
114+
115+
$hierarchy->getSomething();
116+
}
117+
118+
public function testCanProxyMethodAndPropertiesOfParentObjects(): void
119+
{
120+
$hierarchy = new Hierarchy(new class() {
121+
public $bar = 'bar';
122+
private int $count = 0;
123+
124+
public function getCount(): int
125+
{
126+
return ++$this->count;
127+
}
128+
});
129+
$hierarchy = $hierarchy->add(new class() {
130+
public $foo = 'foo';
131+
});
132+
133+
$this->assertSame('foo', $hierarchy->foo());
134+
$this->assertSame('bar', $hierarchy->parent->bar());
135+
$this->assertSame(1, $hierarchy->parent->count());
136+
}
137+
}

0 commit comments

Comments
 (0)