Helper functions with variable amount of arguments
When you want to create a function with either 2 or 3 arguments it gets ugly because PHP gives notices Missing argument 4 for {closure}(), this is unnecessary because php has various ways to deal with a variable amount of arguments.
Will check is there anyway to improve this (last time I try to check this, it's hard to improve because the usage of call_user_func_array) , thanks.
Just use the PHP functionality.
<?php
namespace Test;
use LightnCandy\LightnCandy;
require __DIR__ . '/vendor/autoload.php';
$template = '{{foo "Hello" }} {{foo "world" "!"}} {{bar "Hello" }} {{bar "world" "!"}} {{cb "Hello" }} {{cb "world" "!"}}';
function func1args($arg1, $options) {
return $arg1;
}
function func2args($arg1, $arg2, $options) {
return $arg1 . $arg2;
}
$helpers = [
'foo' => function () {
$args = func_get_args();
return implode('', array_map(function ($value) { return is_string($value) ? $value : '';}, $args));
},
'bar' => function (...$args) {
return implode('', array_map(function ($value) { return is_string($value) ? $value : '';}, $args));
},
'cb' => function (...$args) {
if (count($args) == 2) {
return \Test\func1args(...$args);
}
return \Test\func2args(...$args);
}
];
$phpStr = LightnCandy::compile(
$template,
[
'flags' => LightnCandy::FLAG_ERROR_EXCEPTION | LightnCandy::FLAG_RUNTIMEPARTIAL,
'helpers' => $helpers
]
);
$renderer = LightnCandy::prepare($phpStr);
echo $renderer() . PHP_EOL;
@jayS-de yeah i can see how this can work, however this pushes everything to runtime ..
I tried this in PHP 5.6+ , the helper code is with JS implementation comment :
<?php
use LightnCandy\LightnCandy;
require __DIR__ . '/vendor/autoload.php';
$template = '{{foo "Hello" }} {{foo "world" "!"}}';
$helpers = [
'foo' => function (...$args) {
// Javascript example https://jsfiddle.net/n1yz7ty0/ :
// var args = Array.prototype.slice.call(arguments);
// var options = args.pop();
// return args.join(',');
$options = array_pop($args);
return implode(',', $args);
}
];
$phpStr = LightnCandy::compile(
$template,
[
'flags' => LightnCandy::FLAG_ERROR_EXCEPTION | LightnCandy::FLAG_RUNTIMEPARTIAL,
'helpers' => $helpers
]
);
$renderer = LightnCandy::prepare($phpStr);
echo $renderer();
For PHP 5.6- extra code is required: $args = func_get_args(); . It seems no extra change is required at lightncandy side.
Will add document about this.