Skip to content

Commit 6bdb652

Browse files
authored
fix(view): properly unset local view component variables (#1221)
1 parent f3a21a5 commit 6bdb652

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

packages/view/src/Elements/PhpDataElement.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@ public function compile(): string
3232

3333
// We'll declare the variable in PHP right before the actual element
3434
$variableDeclaration = sprintf(
35-
'$_%sIsLocal = isset($%s) === false; $%s ??= %s ?? null;',
35+
'$_%sIsLocal = $_%sIsLocal ?? isset($%s) === false; $%s ??= %s ?? null;',
36+
$localVariableName,
3637
$localVariableName,
3738
$localVariableName,
3839
$localVariableName,
@@ -44,7 +45,8 @@ public function compile(): string
4445
// And we'll remove it right after the element, this way we've created a "local scope"
4546
// where the variable is only available to that specific element.
4647
$variableRemoval = sprintf(
47-
'if ($_%sIsLocal) { unset($%s); }',
48+
'if ($_%sIsLocal ?? null) { unset($%s); }; unset($_%sIsLocal)',
49+
$localVariableName,
4850
$localVariableName,
4951
$localVariableName,
5052
);

tests/Integration/View/ViewComponentTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -871,4 +871,21 @@ public function test_nested_slots_with_escaping(): void
871871

872872
$this->assertSnippetsMatch('<a>testing</a>', $html);
873873
}
874+
875+
public function test_repeated_local_var_across_view_components(): void
876+
{
877+
$this->registerViewComponent('x-test', '<div :thing="$thing">{{ $thing }}</div>');
878+
879+
$html = $this->render(<<<'HTML'
880+
<x-test thing="a" />
881+
<x-test thing="b" />
882+
<x-test thing="c" />
883+
HTML);
884+
885+
$this->assertSnippetsMatch('
886+
<div thing="a">a</div>
887+
<div thing="b">b</div>
888+
<div thing="c">c</div>
889+
', $html);
890+
}
874891
}

0 commit comments

Comments
 (0)