phpscopetemplate-engineoutput-buffering

Absolute prevention of content pollution in output buffer


I have this following code that basically renders partials. However I was trying to find a way to prevent polluting $templatePath variable into the template (the variable is currently accessible from template which is not what I want). I only want $template and $viewHelper variables to be accessible in the template scope. Do you have any idea?

public function renderComponent(string $templatePath, ViewComponentEntityInterface $component): string
{
        if (! file_exists($templatePath)) {
            throw new RuntimeException('Incorrect component template path: ' . $templatePath);
        }

        $viewHelper = $this->viewHelperFactory->create();

        ob_start();

        try {
            (static function (ViewComponentEntityInterface $template,ViewHelper $viewHelper) use ($templatePath) {
                include $templatePath;
            })($component, $viewHelper);

            return ob_get_clean();
        } catch (Throwable $e) {
            ob_end_clean();

            throw $e;
        }
}

I tried to find something like array_shift but for single variable that would just unset the value and return it at the same time.


Solution

  • Disclaimer: this is just for research purpose. IMHO introducing unnecessary eval is more troublesome than allowing reading $templatePath variable in template.

    The idea in this solution is to create anonymous function where the template path will be constant instead of variable.

    $code = <<<CODE
    \$f = static function (
        ViewComponentEntityInterface \$template,
        ViewHelper \$viewHelper
    ) {
       include $templatePath; 
    }
    CODE;
    eval($code);
    $f($component, $viewHelper);