Skip to content
Open
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
1 change: 1 addition & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ jobs:
code_coverage:
name: Code Coverage
runs-on: ubuntu-latest
continue-on-error: true
steps:
- uses: actions/checkout@v4
- uses: shivammathur/setup-php@v2
Expand Down
9 changes: 8 additions & 1 deletion src/Latte/Essential/CoreExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,8 @@ public function getFilters(): array
'ceil' => $this->filters->ceil(...),
'checkUrl' => $this->filters->checkUrl(...),
'clamp' => $this->filters->clamp(...),
'column' => $this->filters->column(...),
'commas' => $this->filters->commas(...),
'dataStream' => $this->filters->dataStream(...),
'datastream' => $this->filters->dataStream(...),
'date' => $this->filters->date(...),
Expand Down Expand Up @@ -150,6 +152,7 @@ public function getFilters(): array
'join' => $this->filters->implode(...),
'last' => $this->filters->last(...),
'length' => $this->filters->length(...),
'limit' => fn(iterable $value, int $length, int $offset = 0) => Filters::slice($value, $offset, $length, preserveKeys: true),
'localDate' => $this->filters->localDate(...),
'lower' => extension_loaded('mbstring')
? $this->filters->lower(...)
Expand Down Expand Up @@ -210,7 +213,11 @@ public function getPasses(): array
return [
'internalVariables' => $passes->forbiddenVariablesPass(...),
'checkUrls' => $passes->checkUrlsPass(...),
'overwrittenVariables' => Nodes\ForeachNode::overwrittenVariablesPass(...),
'overwrittenVariables' => function (Latte\Compiler\Nodes\TemplateNode $node): void {
if (!$this->engine->hasFeature(Latte\Feature::ScopedLoopVariables)) {
Nodes\ForeachNode::overwrittenVariablesPass($node);
}
},
'customFunctions' => $passes->customFunctionsPass(...),
'moveTemplatePrintToHead' => Nodes\TemplatePrintNode::moveToHeadPass(...),
'nElse' => Nodes\NElseNode::processPass(...),
Expand Down
67 changes: 57 additions & 10 deletions src/Latte/Essential/Filters.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,21 @@ public static function implode(array $arr, string $glue = ''): string
}


/**
* Join array elements with a comma and space.
* @param string[] $arr
*/
public static function commas(array $arr, ?string $lastGlue = null): string
{
if ($lastGlue === null || count($arr) < 2) {
return implode(', ', $arr);
}

$last = array_pop($arr);
return implode(', ', $arr) . $lastGlue . $last;
}


/**
* Splits a string by a string.
* @return list<string>
Expand Down Expand Up @@ -477,7 +492,7 @@ public static function trim(FilterInfo $info, string $s, string $charlist = " \t
/**
* Pad a string to a certain length with another string.
*/
public static function padLeft(string|Stringable|null $s, int $length, string $append = ' '): string
public static function padLeft(string|Stringable|int|float|null $s, int $length, string $append = ' '): string
{
$s = (string) $s;
$length = max(0, $length - self::strLength($s));
Expand All @@ -489,7 +504,7 @@ public static function padLeft(string|Stringable|null $s, int $length, string $a
/**
* Pad a string to a certain length with another string.
*/
public static function padRight(string|Stringable|null $s, int $length, string $append = ' '): string
public static function padRight(string|Stringable|int|float|null $s, int $length, string $append = ' '): string
{
$s = (string) $s;
$length = max(0, $length - self::strLength($s));
Expand All @@ -513,6 +528,17 @@ public static function reverse(string|iterable $val, bool $preserveKeys = false)
}


/**
* Returns the values from a single column in the input array.
* @param iterable<mixed> $data
* @return mixed[]
*/
public static function column(iterable $data, string|int|null $columnKey, string|int|null $indexKey = null): array
{
return array_column(iterator_to_array($data), $columnKey, $indexKey);
}


/**
* Chunks items by returning an array of arrays with the given number of items.
* @param iterable<mixed> $list
Expand Down Expand Up @@ -733,20 +759,41 @@ public static function last(string|array $value): mixed


/**
* Extracts a slice of an array or string.
* @param string|array<mixed> $value
* @return ($value is string ? string : array<mixed>)
* Extracts a slice of an array, string or iterator.
* @param string|iterable<mixed> $value
* @return ($value is string ? string : ($value is array ? array<mixed> : \Generator))
*/
public static function slice(
string|array $value,
string|iterable $value,
int $start,
?int $length = null,
bool $preserveKeys = false,
): string|array
): string|array|\Generator
{
return is_array($value)
? array_slice($value, $start, $length, $preserveKeys)
: self::substring($value, $start, $length);
if (is_string($value)) {
return self::substring($value, $start, $length);
} elseif (is_array($value)) {
return array_slice($value, $start, $length, $preserveKeys);
}

return (function () use ($value, $start, $length, $preserveKeys) {
$i = 0;
$count = 0;
foreach ($value as $key => $val) {
if ($i++ < $start) {
continue;
}
if ($length !== null && $count >= $length) {
break;
}
if ($preserveKeys) {
yield $key => $val;
} else {
yield $val;
}
$count++;
}
})();
}


Expand Down
89 changes: 57 additions & 32 deletions src/Latte/Essential/Nodes/ForeachNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use Latte\Compiler\PrintContext;
use Latte\Compiler\Tag;
use Latte\Compiler\TagParser;
use Latte\Feature;
use function array_map, array_unshift, implode, is_string, preg_match;


Expand Down Expand Up @@ -85,46 +86,52 @@ private static function parseArguments(TagParser $parser, self $node): void
public function print(PrintContext $context): string
{
$content = $this->content->print($context);
$iterator = $this->else || ($this->iterator ?? preg_match('#\$iterator\W|\Wget_defined_vars\W#', $content));
$useIterator = $this->else || ($this->iterator ?? preg_match('#\$iterator\W|\Wget_defined_vars\W#', $content));

$code = $context->format(
"foreach (%raw as %raw) %line { %raw\n}\n",
$useIterator
? $context->format('$iterator = $ʟ_it = new Latte\Essential\CachingIterator(%node, $ʟ_it ?? null)', $this->expression)
: $this->expression->print($context),
$this->printArgs($context),
$this->position,
$content,
);

if ($this->else) {
$content .= $context->format(
'} if ($iterator->isEmpty()) %line { ',
$code .= $context->format(
"if (%raw) %line { %node\n}\n",
$useIterator ? '$iterator->isEmpty()' : $context->format('empty(%node)', $this->expression),
$this->elseLine,
) . $this->else->print($context);
}

if ($iterator) {
return $context->format(
<<<'XX'
foreach ($iterator = $ʟ_it = new Latte\Essential\CachingIterator(%node, $ʟ_it ?? null) as %raw) %line {
%raw
}
$iterator = $ʟ_it = $ʟ_it->getParent();


XX,
$this->expression,
$this->printArgs($context),
$this->position,
$content,
$this->else,
);
}

} else {
return $context->format(
<<<'XX'
foreach (%node as %raw) %line {
%raw
}
if ($useIterator) {
$code .= '$iterator = $ʟ_it = $ʟ_it->getParent();' . "\n";
}

$vars = array_merge($this->key ? $this->collectVariables($this->key) : [], $this->collectVariables($this->value));
if ($vars && !$this->byRef && $context->hasFeature(Feature::ScopedLoopVariables)) {
$backup = '$ʟ_fe_' . $context->generateId();
$unsetList = implode(', ', array_map(fn($var) => $var->print($context), $vars));
$restoreCode = implode('', array_map(fn($var) => $context->format("if (array_key_exists(%dump, $backup)) { %node = &{$backup}[%0.dump]; }\n", $var->name, $var), $vars));
$code = <<<XX
try {
$backup = get_defined_vars();
unset($unsetList);

$code
} finally {
unset($unsetList);
$restoreCode
unset($backup);
}

XX,
$this->expression,
$this->printArgs($context),
$this->position,
$content,
);
XX;
}

return $code . "\n";
}


Expand All @@ -136,6 +143,24 @@ private function printArgs(PrintContext $context): string
}


/**
* Recursively collects variable names from a node (handles ListNode destructuring).
* @return VariableNode[]
*/
private function collectVariables(ExpressionNode|ListNode $node): array
{
$res = [];
if ($node instanceof VariableNode && is_string($node->name)) {
$res[] = $node;
} elseif ($node instanceof ListNode) {
foreach ($node->items as $item) {
$res = array_merge($res, $item ? $this->collectVariables($item->value) : []);
}
}
return $res;
}


public function &getIterator(): \Generator
{
yield $this->expression;
Expand Down
3 changes: 3 additions & 0 deletions src/Latte/Feature.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,7 @@ enum Feature

/** Shows warnings for deprecated Latte 3.0 syntax */
case MigrationWarnings;

/** Variables from {foreach} exist only within the loop */
case ScopedLoopVariables;
}
83 changes: 62 additions & 21 deletions src/Latte/Helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

namespace Latte;

use function array_filter, array_keys, array_search, array_slice, array_unique, count, is_array, is_object, is_string, levenshtein, max, min, strlen, strpos;
use function array_filter, array_keys, array_unique, count, in_array, is_array, is_object, is_string, levenshtein, strlen, strpos;
use const PHP_VERSION_ID;


Expand Down Expand Up @@ -54,45 +54,86 @@ public static function toReflection(mixed $callable): \ReflectionFunctionAbstrac


/**
* Sorts items using topological sort based on before/after constraints.
* @param array<string, mixed|\stdClass> $list
* @return array<string, mixed|\stdClass>
*/
public static function sortBeforeAfter(array $list): array
{
$names = array_keys($list);

// Build adjacency list and in-degree count
// Edge A → B means "A must come before B"
$graph = array_fill_keys($names, []);
$inDegree = array_fill_keys($names, 0);

foreach ($list as $name => $info) {
if (!$info instanceof \stdClass || !($info->before ?? $info->after ?? null)) {
if (!$info instanceof \stdClass) {
continue;
}

unset($list[$name]);
$names = array_keys($list);
$best = null;

foreach ((array) $info->before as $target) {
// "before: X" means this node → X (this comes before X)
foreach ((array) ($info->before ?? []) as $target) {
if ($target === '*') {
$best = 0;
} elseif (isset($list[$target])) {
$pos = (int) array_search($target, $names, strict: true);
$best = min($pos, $best ?? $pos);
foreach ($names as $other) {
if ($other !== $name && !in_array($other, $graph[$name], true)) {
$graph[$name][] = $other;
$inDegree[$other]++;
}
}
} elseif (isset($list[$target]) && $target !== $name) {
if (!in_array($target, $graph[$name], true)) {
$graph[$name][] = $target;
$inDegree[$target]++;
}
}
}

foreach ((array) ($info->after ?? null) as $target) {
// "after: X" means X → this node (X comes before this)
foreach ((array) ($info->after ?? []) as $target) {
if ($target === '*') {
$best = count($names);
} elseif (isset($list[$target])) {
$pos = (int) array_search($target, $names, strict: true);
$best = max($pos + 1, $best);
foreach ($names as $other) {
if ($other !== $name && !in_array($name, $graph[$other], true)) {
$graph[$other][] = $name;
$inDegree[$name]++;
}
}
} elseif (isset($list[$target]) && $target !== $name) {
if (!in_array($name, $graph[$target], true)) {
$graph[$target][] = $name;
$inDegree[$name]++;
}
}
}
}

// Kahn's algorithm
$queue = [];
foreach ($names as $name) {
if ($inDegree[$name] === 0) {
$queue[] = $name;
}
}

$result = [];
while ($queue) {
$node = array_shift($queue);
$result[$node] = $list[$node];

foreach ($graph[$node] as $neighbor) {
$inDegree[$neighbor]--;
if ($inDegree[$neighbor] === 0) {
$queue[] = $neighbor;
}
}
}

$best ??= count($names);
$list = array_slice($list, 0, $best, preserve_keys: true)
+ [$name => $info]
+ array_slice($list, $best, null, preserve_keys: true);
if (count($result) !== count($list)) {
$cycle = array_diff($names, array_keys($result));
throw new \LogicException('Circular dependency detected among: ' . implode(', ', $cycle));
}

return $list;
return $result;
}


Expand Down
2 changes: 1 addition & 1 deletion src/Latte/Runtime/HtmlHelpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public static function escapeText(mixed $s): string
}

$s = htmlspecialchars((string) $s, ENT_NOQUOTES | ENT_SUBSTITUTE, 'UTF-8');
$s = strtr($s, ['{{' => '{<!-- -->{', '{' => '&#123;']);
$s = strtr($s, ['{{' => '&#123;&#123;', '{' => '&#123;']);
return $s;
}

Expand Down
Loading