Skip to content
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

Nested variable override #18

Merged
merged 2 commits into from
May 10, 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
4 changes: 2 additions & 2 deletions src/Exceptions/UndefinedVariableException.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

class UndefinedVariableException extends LiquidException
{
public function __construct(string $method)
public function __construct(string $variable)
{
parent::__construct("Variable `$method` not found");
parent::__construct("Variable `$variable` not found");
}
}
48 changes: 33 additions & 15 deletions src/Nodes/VariableLookup.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
use Keepsuit\Liquid\Contracts\HasParseTreeVisitorChildren;
use Keepsuit\Liquid\Contracts\IsContextAware;
use Keepsuit\Liquid\Exceptions\SyntaxException;
use Keepsuit\Liquid\Exceptions\UndefinedVariableException;
use Keepsuit\Liquid\Parse\LexerOptions;
use Keepsuit\Liquid\Render\RenderContext;
use Keepsuit\Liquid\Support\MissingValue;
use Keepsuit\Liquid\Support\Str;

class VariableLookup implements CanBeEvaluated, HasParseTreeVisitorChildren
Expand Down Expand Up @@ -80,30 +82,46 @@ public function evaluate(RenderContext $context): mixed
{
$name = $context->evaluate($this->name);
assert(is_string($name));
$object = $context->findVariable($name);
$variables = $context->findVariables($name);

if ($object instanceof \Generator && $this->lookups !== []) {
$object = iterator_to_array($object, preserve_keys: false);
if ($this->lookups === []) {
return $variables[0] ?? null;
}

foreach ($this->lookups as $i => $lookup) {
$key = $context->evaluate($lookup) ?? '';
foreach ($variables as $object) {
if ($object instanceof \Generator) {
$object = iterator_to_array($object, preserve_keys: false);
}

foreach ($this->lookups as $i => $lookup) {
$key = $context->evaluate($lookup) ?? '';

assert(is_string($key) || is_int($key));
assert(is_string($key) || is_int($key));

$object = match (true) {
is_array($object) && array_key_exists($key, $object) => $context->lookupAndEvaluate($object, $key),
is_object($object) => $context->lookupAndEvaluate($object, $key),
in_array($i, $this->lookupFilters) => $this->applyFilter($context, $object, (string) $key),
default => $context->lookupAndEvaluate($object, $key),
};
$object = match (true) {
is_array($object) && array_key_exists($key, $object) => $context->internalContextLookup($object, $key),
is_object($object) => $context->internalContextLookup($object, $key),
in_array($i, $this->lookupFilters) => $this->applyFilter($context, $object, (string) $key),
default => $context->internalContextLookup($object, $key),
};

if ($object instanceof IsContextAware) {
$object->setContext($context);
if ($object instanceof MissingValue) {
continue 2;
}

if ($object instanceof IsContextAware) {
$object->setContext($context);
}
}

return $object;
}

if ($context->strictVariables) {
throw new UndefinedVariableException($this->toString());
}

return $object;
return null;
}

protected function applyFilter(RenderContext $context, mixed $object, string $filter): mixed
Expand Down
51 changes: 15 additions & 36 deletions src/Render/RenderContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -171,53 +171,32 @@ public function has(string $key): bool
/**
* @throws UndefinedVariableException
*/
public function findVariable(string $key): mixed
public function findVariables(string $key): array
{
$scope = Arr::first($this->scopes, fn (array $scope) => array_key_exists($key, $scope));
$variables = [];

$variable = is_array($scope)
? $this->internalContextLookup($scope, $key)
: $this->tryFindVariableInEnvironments($key);

if ($variable instanceof MissingValue) {
return $this->strictVariables ? throw new UndefinedVariableException($key) : null;
foreach ($this->scopes as $scope) {
$variables[] = $this->internalContextLookup($scope, $key);
}
$variables[] = $this->internalContextLookup($this->environment, $key);
$variables[] = $this->internalContextLookup($this->sharedState->staticEnvironment, $key);

if ($variable instanceof IsContextAware) {
$variable->setContext($this);
}
$variables = array_values(array_filter($variables, fn (mixed $value) => ! $value instanceof MissingValue));

return $variable;
}

/**
* @throws UndefinedVariableException
*/
public function lookupAndEvaluate(mixed $scope, int|string $key): mixed
{
$value = match (true) {
is_array($scope) || is_object($scope) => $this->internalContextLookup($scope, $key),
default => new MissingValue(),
};

if ($value instanceof MissingValue) {
return $this->strictVariables ? throw new UndefinedVariableException((string) $key) : null;
if ($variables === []) {
return $this->strictVariables ? throw new UndefinedVariableException($key) : [];
}

return $value;
}

protected function tryFindVariableInEnvironments(string $key): mixed
{
$foundVariable = $this->internalContextLookup($this->environment, $key);
if (! $foundVariable instanceof MissingValue) {
return $foundVariable;
foreach ($variables as $variable) {
if ($variable instanceof IsContextAware) {
$variable->setContext($this);
}
}

return $this->internalContextLookup($this->sharedState->staticEnvironment, $key);
return $variables;
}

public function internalContextLookup(array|object $scope, int|string $key): mixed
public function internalContextLookup(mixed $scope, int|string $key): mixed
{
$value = match (true) {
is_array($scope) && array_key_exists($key, $scope) => $scope[$key],
Expand Down
4 changes: 2 additions & 2 deletions tests/Integration/TemplateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,9 @@
->{0}->toBeInstanceOf(UndefinedVariableException::class)
->{0}->getMessage()->toBe('Variable `y` not found')
->{1}->toBeInstanceOf(UndefinedVariableException::class)
->{1}->getMessage()->toBe('Variable `b` not found')
->{1}->getMessage()->toBe('Variable `z.b` not found')
->{2}->toBeInstanceOf(UndefinedVariableException::class)
->{2}->getMessage()->toBe('Variable `d` not found');
->{2}->getMessage()->toBe('Variable `z.c.d` not found');
});

test('null value does not throw exception', function () {
Expand Down
33 changes: 33 additions & 0 deletions tests/Integration/VariableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,39 @@
assertTemplateResult('1', '{{test.first}}', ['test' => generator()]);
});

test('variable override', function () {
$templateFactory = new \Keepsuit\Liquid\TemplateFactory();
$templateFactory->registerTag(\Keepsuit\Liquid\Tests\Stubs\VariableOverrideTag::class);

assertTemplateResult('old|new|old', <<<'LIQUID'
{{ test }}|
{%- override test "new" -%}
{{ test }}|
{%- endoverride -%}
{{ test }}
LIQUID, [
'test' => 'old',
], factory: $templateFactory);
});

test('variable nested override', function () {
$templateFactory = new \Keepsuit\Liquid\TemplateFactory();
$templateFactory->registerTag(\Keepsuit\Liquid\Tests\Stubs\VariableOverrideTag::class);

assertTemplateResult('old_a,old_b|old_a,new_b|old_a,old_b', <<<'LIQUID'
{{ test.a }},{{ test.b }}|
{%- override test.b "new_b" -%}
{{ test.a }},{{ test.b }}|
{%- endoverride -%}
{{ test.a }},{{ test.b }}
LIQUID, [
'test' => [
'a' => 'old_a',
'b' => 'old_b',
],
], factory: $templateFactory);
});

function generator(): Generator
{
yield '1';
Expand Down
53 changes: 53 additions & 0 deletions tests/Stubs/VariableOverrideTag.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

namespace Keepsuit\Liquid\Tests\Stubs;

use Keepsuit\Liquid\Exceptions\SyntaxException;
use Keepsuit\Liquid\Nodes\BodyNode;
use Keepsuit\Liquid\Nodes\Variable;
use Keepsuit\Liquid\Nodes\VariableLookup;
use Keepsuit\Liquid\Parse\TagParseContext;
use Keepsuit\Liquid\Render\RenderContext;
use Keepsuit\Liquid\TagBlock;

class VariableOverrideTag extends TagBlock
{
protected BodyNode $body;

protected Variable $variable;

protected mixed $value;

public function parse(TagParseContext $context): static
{
assert($context->body !== null);
$this->body = $context->body;

$this->variable = $context->params->variable();

$this->value = $context->params->expression();

$context->params->assertEnd();

return $this;
}

public function render(RenderContext $context): string
{
return $context->stack(function (RenderContext $context) {
$name = $this->variable->name;

$context->set(match (true) {
$name instanceof VariableLookup, is_string($name) => (string) $name,
default => throw new SyntaxException('Invalid variable name'),
}, $this->value);

return $this->body->render($context);
});
}

public static function tagName(): string
{
return 'override';
}
}