50 lines
1.6 KiB
PHP
50 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace Picea\ControlStructure;
|
|
|
|
class FunctionToken implements ControlStructure {
|
|
|
|
public array $token = [ "function", "endfunction", "return" ];
|
|
|
|
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string {
|
|
switch($token) {
|
|
case "function":
|
|
$context->functions++;
|
|
|
|
return $this->printFunction($context, $arguments);
|
|
|
|
case "return":
|
|
if ( empty($context->functions) ) {
|
|
throw new \RuntimeException("A function return tag {% return %} was found without an opening {% function ... %} tag");
|
|
}
|
|
|
|
return $this->printReturn($context, $arguments);
|
|
|
|
case "endfunction":
|
|
if ( empty($context->functions) ) {
|
|
throw new \RuntimeException("A function closing tag {% endfunction %} was found without an opening {% function ... %} tag");
|
|
}
|
|
|
|
$context->functions--;
|
|
|
|
return $this->printEndFunction($context);
|
|
}
|
|
}
|
|
|
|
protected function printFunction($context, ?string $arguments) : string
|
|
{
|
|
$name = trim(explode('(', $arguments, 2)[0]);
|
|
|
|
return "<?php if (! function_exists(__NAMESPACE__ . '\\$name')) { function $arguments { ?>";
|
|
}
|
|
|
|
protected function printReturn($context, ?string $arguments) : string
|
|
{
|
|
return "<?php return $arguments; ?>";
|
|
}
|
|
|
|
protected function printEndFunction($context) : string
|
|
{
|
|
return "<?php } } ?>";
|
|
}
|
|
} |