Skip to content

Commit 2624ba5

Browse files
committed
Handle blocks with a non-simple path and explicit params
Also moved some duplicated code to reusable functions.
1 parent b4a562e commit 2624ba5

3 files changed

Lines changed: 167 additions & 108 deletions

File tree

‎src/Compiler.php‎

Lines changed: 83 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -184,9 +184,7 @@ private function BlockStatement(BlockStatement $block): string
184184

185185
// Regular section: {{#"foo"}}...{{/"foo"}}
186186
$body = $this->compileProgram($block->program, true);
187-
$else = $block->inverse
188-
? ", function(\$cx, \$in) {return " . $this->compileProgram($block->inverse) . ";}"
189-
: '';
187+
$else = $this->compileElseClause($block);
190188
return "'." . $this->getFuncName('sec', "\$cx, $var, null, \$in, false, function(\$cx, \$in) use (&\$sp) {return $body;}$else") . ").'";
191189
}
192190

@@ -195,10 +193,26 @@ private function BlockStatement(BlockStatement $block): string
195193
return $this->compileInvertedSection($block);
196194
}
197195

196+
// Non-simple path with params: invoke as a dynamic block helper call
197+
if ($block->params) {
198+
return $this->compileDynamicBlockHelper($block);
199+
}
200+
198201
// Regular section: {{#var}}...{{/var}}
199202
return $this->compileSection($block);
200203
}
201204

205+
private function compileDynamicBlockHelper(BlockStatement $block): string
206+
{
207+
$varPath = $this->compileExpression($block->path);
208+
$bp = $block->program->blockParams;
209+
$params = $this->compileParams($block->params, $block->hash, $bp ?: null);
210+
$body = $this->compileProgramWithBlockParams($block->program, $bp);
211+
$else = $this->compileElseClause($block);
212+
213+
return "'." . $this->getFuncName('dynhbbch', "\$cx, $varPath, $params, \$in, function(\$cx, \$in) {return $body;}$else") . ").'";
214+
}
215+
202216
private function resolveHelper(string $helperName): bool
203217
{
204218
if (isset($this->context->helpers[$helperName])) {
@@ -253,17 +267,8 @@ private function compileEach(BlockStatement $block): string
253267
$bp = $block->program ? $block->program->blockParams : [];
254268
$bs = $bp ? Expression::listString($bp) : 'null';
255269

256-
if ($bp) {
257-
array_unshift($this->blockParamValues, $bp);
258-
}
259-
$body = $block->program ? $this->compileProgram($block->program, true) : "''";
260-
if ($bp) {
261-
array_shift($this->blockParamValues);
262-
}
263-
264-
$else = $block->inverse
265-
? ", function(\$cx, \$in) {return " . $this->compileProgram($block->inverse) . ";}"
266-
: '';
270+
$body = $block->program ? $this->compileProgramWithBlockParams($block->program, $bp, true) : "''";
271+
$else = $this->compileElseClause($block);
267272

268273
return "'." . $this->getFuncName('sec', "\$cx, LR::dv($var, \$in), $bs, \$in, true, function(\$cx, \$in) use (&\$sp) {return $body;}$else") . ").'";
269274
}
@@ -279,9 +284,7 @@ private function compileWith(BlockStatement $block): string
279284
$bs = $bp ? Expression::listString($bp) : 'null';
280285

281286
$body = $block->program ? $this->compileProgram($block->program) : "''";
282-
$else = $block->inverse
283-
? ", function(\$cx, \$in) {return " . $this->compileProgram($block->inverse) . ";}"
284-
: '';
287+
$else = $this->compileElseClause($block);
285288

286289
return "'." . $this->getFuncName('wi', "\$cx, LR::dv($var, \$in), $bs, \$in, function(\$cx, \$in) {return $body;}$else") . ").'";
287290
}
@@ -291,9 +294,7 @@ private function compileSection(BlockStatement $block): string
291294
$var = $this->compileExpression($block->path);
292295

293296
$body = $block->program ? $this->compileProgram($block->program, true) : "''";
294-
$else = $block->inverse
295-
? ", function(\$cx, \$in) {return " . $this->compileProgram($block->inverse) . ";}"
296-
: '';
297+
$else = $this->compileElseClause($block);
297298

298299
return "'." . $this->getFuncName('sec', "\$cx, $var, null, \$in, false, function(\$cx, \$in) use (&\$sp) {return $body;}$else") . ").'";
299300
}
@@ -324,16 +325,8 @@ private function compileBlockHelper(BlockStatement $block, string $helperName):
324325
return "'." . $this->getFuncName('hbbch', "\$cx, '$helperName', $params, \$in, true, function(\$cx, \$in) {return $body;}") . ").'";
325326
}
326327

327-
if ($bp) {
328-
array_unshift($this->blockParamValues, $bp);
329-
}
330-
$body = $this->compileProgram($block->program);
331-
if ($bp) {
332-
array_shift($this->blockParamValues);
333-
}
334-
$else = $block->inverse
335-
? ", function(\$cx, \$in) {return " . $this->compileProgram($block->inverse) . ";}"
336-
: '';
328+
$body = $this->compileProgramWithBlockParams($block->program, $bp);
329+
$else = $this->compileElseClause($block);
337330

338331
return "'." . $this->getFuncName('hbbch', "\$cx, '$helperName', $params, \$in, false, function(\$cx, \$in) {return $body;}$else") . ").'";
339332
}
@@ -581,16 +574,7 @@ private function PathExpression(PathExpression $expression): string
581574
$depth = $expression->depth;
582575
$parts = $expression->parts;
583576

584-
$base = $data ? '$cx->spVars' : '$in';
585-
586-
// Handle depth (../ traversal)
587-
if ($depth > 0) {
588-
if ($data) {
589-
$base .= str_repeat("['_parent']", $depth);
590-
} else {
591-
$base = "\$cx->scopes[count(\$cx->scopes)-$depth]";
592-
}
593-
}
577+
$base = $this->buildBasePath($data, $depth);
594578

595579
// Filter out SubExpression parts for string-only operations
596580
$stringParts = array_values(array_filter($parts, fn($p) => is_string($p)));
@@ -615,28 +599,19 @@ private function PathExpression(PathExpression $expression): string
615599
if ($bpIdx !== null) {
616600
$escapedName = addcslashes($stringParts[0], "'\\");
617601
$bpBase = "\$cx->blParam[$bpIdx]['$escapedName']";
618-
$remaining = '';
619-
foreach (array_slice($stringParts, 1) as $part) {
620-
$remaining .= "['" . addcslashes($part, "'\\") . "']";
621-
}
602+
$remaining = $this->buildKeyAccess(array_slice($stringParts, 1));
622603
return "$bpBase$remaining ?? $miss";
623604
}
624605
}
625606

626607
// Build array access string
627-
$n = '';
628-
foreach ($stringParts as $part) {
629-
$n .= "['" . addcslashes($part, "'\\") . "']";
630-
}
608+
$n = $this->buildKeyAccess($stringParts);
631609

632610
// Handle .length special case
633611
$lastPart = end($stringParts);
634612
if ($lastPart === 'length') {
635613
$varParts = array_slice($stringParts, 0, -1);
636-
$p = '';
637-
foreach ($varParts as $part) {
638-
$p .= "['" . addcslashes($part, "'\\") . "']";
639-
}
614+
$p = $this->buildKeyAccess($varParts);
640615

641616
$checks = [];
642617
if ($depth > 0) {
@@ -881,6 +856,60 @@ private function getSimpleHelperName(PathExpression|Literal $path): ?string
881856
return $path->parts[0];
882857
}
883858

859+
/**
860+
* Compile the else/inverse clause of a block as a trailing closure argument, or '' if absent.
861+
*/
862+
private function compileElseClause(BlockStatement $block): string
863+
{
864+
return $block->inverse
865+
? ", function(\$cx, \$in) {return " . $this->compileProgram($block->inverse) . ";}"
866+
: '';
867+
}
868+
869+
/**
870+
* Compile a block program, pushing/popping block params around the compilation.
871+
* @param string[] $bp
872+
*/
873+
private function compileProgramWithBlockParams(Program $program, array $bp, bool $withSp = false): string
874+
{
875+
if ($bp) {
876+
array_unshift($this->blockParamValues, $bp);
877+
}
878+
$body = $this->compileProgram($program, $withSp);
879+
if ($bp) {
880+
array_shift($this->blockParamValues);
881+
}
882+
return $body;
883+
}
884+
885+
/**
886+
* Build the base path expression for a given data flag and depth.
887+
*/
888+
private function buildBasePath(bool $data, int $depth): string
889+
{
890+
$base = $data ? '$cx->spVars' : '$in';
891+
if ($depth > 0) {
892+
$base = $data
893+
? $base . str_repeat("['_parent']", $depth)
894+
: "\$cx->scopes[count(\$cx->scopes)-$depth]";
895+
}
896+
return $base;
897+
}
898+
899+
/**
900+
* Build a chained array-access string for the given path parts.
901+
* e.g. ['foo', 'bar'] → "['foo']['bar']"
902+
* @param string[] $parts
903+
*/
904+
private function buildKeyAccess(array $parts): string
905+
{
906+
$n = '';
907+
foreach ($parts as $part) {
908+
$n .= "['" . addcslashes($part, "'\\") . "']";
909+
}
910+
return $n;
911+
}
912+
884913
/**
885914
* Build function call with optional strict-mode debug wrapping.
886915
*/
@@ -950,20 +979,8 @@ private function compilePathWithLookup(PathExpression $path, string $lookupCode)
950979
$depth = $path->depth;
951980
$parts = array_values(array_filter($path->parts, fn($p) => is_string($p)));
952981

953-
$base = $data ? '$cx->spVars' : '$in';
954-
955-
if ($depth > 0) {
956-
if ($data) {
957-
$base .= str_repeat("['_parent']", $depth);
958-
} else {
959-
$base = "\$cx->scopes[count(\$cx->scopes)-$depth]";
960-
}
961-
}
962-
963-
$n = '';
964-
foreach ($parts as $part) {
965-
$n .= "['" . addcslashes($part, "'\\") . "']";
966-
}
982+
$base = $this->buildBasePath($data, $depth);
983+
$n = $this->buildKeyAccess($parts);
967984

968985
$miss = $this->context->options->strict
969986
? "LR::miss('" . addcslashes($path->original, "'\\") . "')"

‎src/Runtime.php‎

Lines changed: 84 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -412,33 +412,85 @@ public static function hbch(RuntimeContext $cx, string $ch, array $vars, mixed &
412412
*/
413413
public static function hbbch(RuntimeContext $cx, string $ch, array $vars, mixed &$_this, bool $inverted, ?\Closure $cb, ?\Closure $else = null): mixed
414414
{
415-
$blockParams = 0;
415+
$blockParams = isset($vars[2]) ? count($vars[2]) : 0;
416416
$data = &$cx->spVars;
417417

418-
if (isset($vars[2])) {
419-
$blockParams = count($vars[2]);
420-
}
421-
422418
// invert the logic
423419
if ($inverted) {
424420
$tmp = $else;
425421
$else = $cb;
426422
$cb = $tmp;
427423
}
428424

429-
$fn = function ($context = null, $data = null) use ($cx, $_this, $cb, $vars) {
425+
$options = new HelperOptions(
426+
name: $ch,
427+
hash: $vars[1],
428+
fn: static::makeBlockFn($cx, $_this, $cb, $vars),
429+
inverse: static::makeInverseFn($cx, $_this, $else),
430+
blockParams: $blockParams,
431+
scope: $_this,
432+
data: $data,
433+
);
434+
435+
return static::applyBlockHelperMissing($cx, static::exch($cx, $ch, $vars, $options), $_this, $cb, $else);
436+
}
437+
438+
/**
439+
* Like hbbch but for non-registered paths (pathed/depthed/scoped block calls with params).
440+
* If $callable is not callable, falls back to sec() using it as a section value.
441+
* @param array<array<mixed>|string|int> $vars variables for the helper
442+
* @param array<string,array<mixed>|string|int> $_this current rendering context for the helper
443+
* @param \Closure|null $cb callback function to render child context
444+
* @param \Closure|null $else callback function to render child context when {{else}}
445+
*/
446+
public static function dynhbbch(RuntimeContext $cx, mixed $callable, array $vars, mixed &$_this, ?\Closure $cb, ?\Closure $else = null): mixed
447+
{
448+
if (!is_callable($callable)) {
449+
return static::sec($cx, $callable, null, $_this, false, $cb, $else);
450+
}
451+
452+
$blockParams = isset($vars[2]) ? count($vars[2]) : 0;
453+
$data = &$cx->spVars;
454+
455+
$options = new HelperOptions(
456+
name: '',
457+
hash: $vars[1],
458+
fn: static::makeBlockFn($cx, $_this, $cb, $vars),
459+
inverse: static::makeInverseFn($cx, $_this, $else),
460+
blockParams: $blockParams,
461+
scope: $_this,
462+
data: $data,
463+
);
464+
465+
$args = $vars[0];
466+
$args[] = $options;
467+
try {
468+
$result = $callable(...$args);
469+
} catch (\Throwable $e) {
470+
throw new \Exception('Runtime: dynamic block helper error: ' . $e->getMessage());
471+
}
472+
473+
return static::applyBlockHelperMissing($cx, $result, $_this, $cb, $else);
474+
}
475+
476+
/**
477+
* Build the $fn closure passed to HelperOptions for block helpers.
478+
* Handles spVars updates, block-param injection, and context scope pushing.
479+
*
480+
* @param array<array<mixed>|string|int> $vars
481+
*/
482+
private static function makeBlockFn(RuntimeContext $cx, mixed $_this, ?\Closure $cb, array $vars): \Closure
483+
{
484+
return function ($context = null, $data = null) use ($cx, $_this, $cb, $vars) {
430485
$cx = clone $cx;
431486
$old_spvar = $cx->spVars;
432487
if (isset($data['data'])) {
433488
$cx->spVars = array_merge(['root' => $old_spvar['root']], $data['data'], ['_parent' => $old_spvar]);
434489
}
435490

436-
$ex = false;
437491
if (isset($data['blockParams'], $vars[2])) {
438492
$ex = array_combine($vars[2], array_slice($data['blockParams'], 0, count($vars[2])));
439493
array_unshift($cx->blParam, $ex);
440-
} elseif (isset($cx->blParam[0])) {
441-
$ex = $cx->blParam[0];
442494
}
443495

444496
if ($context === null || $context === $_this) {
@@ -454,43 +506,38 @@ public static function hbbch(RuntimeContext $cx, string $ch, array $vars, mixed
454506
}
455507
return $ret;
456508
};
509+
}
457510

458-
if ($else) {
459-
$inverse = function ($context = null) use ($cx, $_this, $else) {
511+
/**
512+
* Build the $inverse closure passed to HelperOptions for block helpers.
513+
*/
514+
private static function makeInverseFn(RuntimeContext $cx, mixed $_this, ?\Closure $else): \Closure
515+
{
516+
return $else
517+
? function ($context = null) use ($cx, $_this, $else) {
460518
if ($context === null) {
461-
$ret = $else($cx, $_this);
462-
} else {
463-
$cx->scopes[] = $_this;
464-
$ret = $else($cx, $context);
465-
array_pop($cx->scopes);
519+
return $else($cx, $_this);
466520
}
521+
$cx->scopes[] = $_this;
522+
$ret = $else($cx, $context);
523+
array_pop($cx->scopes);
467524
return $ret;
468-
};
469-
} else {
470-
$inverse = function () {
471-
return '';
472-
};
473-
}
474-
475-
$options = new HelperOptions(
476-
name: $ch,
477-
hash: $vars[1],
478-
fn: $fn,
479-
inverse: $inverse,
480-
blockParams: $blockParams,
481-
scope: $_this,
482-
data: $data,
483-
);
484-
485-
$result = static::exch($cx, $ch, $vars, $options);
525+
}
526+
: fn() => '';
527+
}
486528

487-
// If the helper returned a string, it managed its own rendering (called options.fn())
529+
/**
530+
* Apply blockHelperMissing semantics: if the helper returned a string/SafeString,
531+
* pass it through; otherwise treat the return value as a section context.
532+
*/
533+
private static function applyBlockHelperMissing(RuntimeContext $cx, mixed $result, mixed $_this, ?\Closure $cb, ?\Closure $else): string
534+
{
488535
if (is_string($result) || $result instanceof SafeString) {
489536
return $result;
490537
}
491538

492-
// Otherwise apply blockHelperMissing semantics: use the return value as the block context
493-
return static::sec($cx, $result, null, $_this, false, $cb, $else);
539+
// $cb may be null (inverted block with no else clause) after the inversion swap in hbbch
540+
return static::sec($cx, $result, null, $_this, false, $cb ?? static fn() => '', $else);
494541
}
495542

496543
/**

0 commit comments

Comments
 (0)