Skip to content

Commit

Permalink
[BUGFIX] Explicitly set variables override local variables (#849)
Browse files Browse the repository at this point in the history
  • Loading branch information
s2b authored Dec 11, 2023
1 parent d521f00 commit 5b8a5cc
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 1 deletion.
12 changes: 12 additions & 0 deletions Documentation/Usage/Syntax.rst
Original file line number Diff line number Diff line change
Expand Up @@ -200,3 +200,15 @@ the scope:
<f:variable name="lastItem" value="{item}" />
</f:for>
<!-- {lastItem} is "second" -->
If a global variable is created inside a local scope and uses the same name as a local
variable, it will still leak out of the scope and will also be valid inside the scope:

.. code-block:: xml
<f:for each="{0: 'first', 1: 'second'}" as="item">
<!-- {item} is "first" or "second" -->
<f:variable name="item" value="overwritten" />
<!-- {item} is "overwritten" -->
</f:for>
<!-- {item} is "overwritten" -->
1 change: 1 addition & 0 deletions src/Core/Variables/ScopedVariableProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public function getLocalVariableProvider(): VariableProviderInterface
public function add($identifier, $value): void
{
$this->globalVariables->add($identifier, $value);
$this->localVariables->add($identifier, $value);
}

/**
Expand Down
7 changes: 7 additions & 0 deletions tests/Functional/ViewHelpers/ForViewHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,13 @@ public static function renderDataProvider(): \Generator
'overwritten',
];

$value = ['bar', 2];
yield 'local variables can be converted to global variables inside loop' => [
'<f:for each="{value}" as="item">{item}|<f:variable name="item" value="overwritten" />{item}|</f:for>{item}',
['value' => $value],
'bar|overwritten|2|overwritten|overwritten',
];

$value = ['bar', 2];
yield 'variables set inside loop can be used after loop' => [
'<f:for each="{value}" key="key" as="item"><f:variable name="foo" value="bar" /></f:for>{foo}',
Expand Down
2 changes: 1 addition & 1 deletion tests/Unit/Core/Variables/ScopedVariableProviderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ public function addVariable()
$variableProvider = new ScopedVariableProvider(new StandardVariableProvider(), new StandardVariableProvider());
$variableProvider->add('globalVar', 'global');
self::assertEquals('global', $variableProvider->getGlobalVariableProvider()->get('globalVar'));
self::assertNull($variableProvider->getLocalVariableProvider()->get('globalVar'));
self::assertEquals('global', $variableProvider->getLocalVariableProvider()->get('globalVar'));
}

/**
Expand Down

0 comments on commit 5b8a5cc

Please sign in to comment.