Skip to content

Commit

Permalink
Allow registering functions in BlockHelper
Browse files Browse the repository at this point in the history
  • Loading branch information
thekid committed Jul 23, 2023
1 parent 6b1189e commit 412fac9
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 13 deletions.
20 changes: 12 additions & 8 deletions src/main/php/com/handlebarsjs/BlockHelpers.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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));
}
Expand Down
13 changes: 8 additions & 5 deletions src/main/php/com/handlebarsjs/HandlebarsParser.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 412fac9

Please sign in to comment.