picea/src/ControlStructure/AbstractLoop.php
2025-10-15 14:59:31 +00:00

46 lines
1.2 KiB
PHP

<?php
namespace Picea\ControlStructure;
abstract class AbstractLoop implements ControlStructure {
protected function openLoop(\Picea\Compiler\Context &$context, ?string $arguments, string $token,) : string
{
$name = "$".uniqid("{$token}_");
$stack = array_filter($context->iterationStack ?? [], function($item) {
return ! $item['or'];
});
$count = count($stack);
if ( $count > 0 ) {
$name .= "[" . end($stack)['uid'] . "]";
}
$context->iterationStack[] = [
'or' => false,
'uid' => $name,
'token' => "end{$token}",
];
return "<?php $token ($arguments): \$__loop_index = $name = ( $name ?? 0 ) + 1; ?>";
}
protected function closeLoop(\Picea\Compiler\Context &$context, ?string $arguments, string $token,) : string
{
$last = end($context->iterationStack);
if ( $last['or'] === false ) {
$output = "<?php $token; ?>";
}
else {
$output = "<?php endif; if ( isset({$last['uid']}) ) unset({$last['uid']}); ?>";
}
array_pop($context->iterationStack);
return $output;
}
}