schranz-templating / templating

A template abstraction prototype for php template engines.
MIT License
23 stars 0 forks source link

Bridge Template Functions to Blade Template Engine #4

Open alexander-schranz opened 2 years ago

alexander-schranz commented 2 years ago

To allow registering function for Blade Template Engine we need generate or eval some code. As example:

https://3v4l.org/fJXiL

<?php

$registry = [
    'asdf0' => function(string $test) { echo 'asdf0_' . $test . PHP_EOL; },
    'asdf1' => function(string $test) { echo 'asdf1_' . $test . PHP_EOL; },
    'asdf2' => function(string $test) { echo 'asdf2_' . $test . PHP_EOL; },
];

class BladeFunctionLocator {
    /** @var array<string, callable> */
    public static $registry = [];
    public static function call($functionName, $args) {
        static::$registry[$functionName](...$args);
    }

    public static function registerFunctions(): void {
        // start the black magic

        $functionCode = '';
        foreach (\array_keys(static::$registry) as $functionName) {
            if (\function_exists($functionName)) {
                throw new \RuntimeException('Function with name "' . $functionName . '" already registered.');
            }

            $functionCode .= 'function ' . $functionName . '(...$args) { return BladeFunctionLocator::call(__FUNCTION__, $args); };';
        }

        // SOME EVIL EVAL πŸ™ˆπŸ™ˆπŸ™ˆπŸ™ˆπŸ™ˆπŸ™ˆπŸ™ˆπŸ™ˆ SOME EVIL EVAL πŸ™ˆπŸ™ˆπŸ™ˆπŸ™ˆπŸ™ˆπŸ™ˆπŸ™ˆπŸ™ˆ SOME EVIL EVAL
        eval($functionCode);

        // end the black magic
    }
}

BladeFunctionLocator::$registry = $registry;
BladeFunctionLocator::registerFunctions();

asdf0('0');
asdf1('1');
asdf2('2');