From 412fac931868cf0b9c637b47fc51e795edd6a1ed Mon Sep 17 00:00:00 2001 From: Timm Friebe Date: Sun, 23 Jul 2023 23:27:21 +0200 Subject: [PATCH] Allow registering functions in BlockHelper --- .../com/handlebarsjs/BlockHelpers.class.php | 20 +++++++++++-------- .../handlebarsjs/HandlebarsParser.class.php | 13 +++++++----- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/src/main/php/com/handlebarsjs/BlockHelpers.class.php b/src/main/php/com/handlebarsjs/BlockHelpers.class.php index 15a2759..35439c0 100755 --- a/src/main/php/com/handlebarsjs/BlockHelpers.class.php +++ b/src/main/php/com/handlebarsjs/BlockHelpers.class.php @@ -2,23 +2,29 @@ /** Block helpers factory */ class BlockHelpers { - private $impl; + private $impl= []; - /** @param [:string] $impl */ - public function __construct($impl) { - $this->impl= $impl; + /** @param [:string] $byName */ + public function __construct($byName) { + foreach ($byName as $name => $impl) { + $this->register($name, $impl); + } } /** * Register a named implementation * * @param string $name - * @param ?string $impl + * @param ?string|function(var[], com.github.ParseState): com.github.mustache.Node $impl * @return self */ public function register($name, $impl) { if (null === $impl) { unset($this->impl[$name]); + } else if (is_string($impl)) { + $this->impl[$name]= function($options, $state) use($impl) { + return $state->target->add(new $impl($options, null, null, $state->start, $state->end)); + }; } else { $this->impl[$name]= $impl; } @@ -39,9 +45,7 @@ public function register($name, $impl) { public function newInstance($options, $state) { $name= array_shift($options); if ($impl= $this->impl[$name] ?? null) { - return $state->target->add(new $impl($options, null, null, $state->start, $state->end)); - } else if ('*inline' === $name) { - return new BlockNode('inline', $options, $state->parents[0]->declare($options[0] ?? null)); + return $impl($options, $state); } else { return $state->target->add(new BlockNode($name, $options, null, null, $state->start, $state->end)); } diff --git a/src/main/php/com/handlebarsjs/HandlebarsParser.class.php b/src/main/php/com/handlebarsjs/HandlebarsParser.class.php index a41bcda..49194fe 100755 --- a/src/main/php/com/handlebarsjs/HandlebarsParser.class.php +++ b/src/main/php/com/handlebarsjs/HandlebarsParser.class.php @@ -109,11 +109,14 @@ public function options($tag) { */ protected function initialize() { $this->blocks= new BlockHelpers([ - 'if' => IfBlockHelper::class, - 'unless' => UnlessBlockHelper::class, - 'with' => WithBlockHelper::class, - 'each' => EachBlockHelper::class, - '>' => PartialBlockHelper::class, + 'if' => IfBlockHelper::class, + 'unless' => UnlessBlockHelper::class, + 'with' => WithBlockHelper::class, + 'each' => EachBlockHelper::class, + '>' => PartialBlockHelper::class, + '*inline' => function($options, $state) { + return new BlockNode('inline', [], $state->parents[0]->declare($options[0] ?? null)); + } ]); // Sections