LightnCandy\LightnCandy::prepare PHP Method

prepare() public static method

Get a working render function by a string of PHP code. This method may requires php setting allow_url_include=1 and allow_url_fopen=1 , or access right to tmp file system.
Deprecation:
public static prepare ( string $php, string | null $tmpDir = null, boolean $delete = true ) : Closure | false
$php string PHP code
$tmpDir string | null Optional, change temp directory for php include file saved by prepare() when cannot include PHP code with data:// format.
$delete boolean Optional, delete temp php file when set to tru. Default is true, set it to false for debug propose
return Closure | false result of include()
    public static function prepare($php, $tmpDir = null, $delete = true)
    {
        $php = "<?php {$php} ?>";
        if (!ini_get('allow_url_include') || !ini_get('allow_url_fopen')) {
            if (!is_string($tmpDir) || !is_dir($tmpDir)) {
                $tmpDir = sys_get_temp_dir();
            }
        }
        if (is_dir($tmpDir)) {
            $fn = tempnam($tmpDir, 'lci_');
            if (!$fn) {
                error_log("Can not generate tmp file under {$tmpDir}!!\n");
                return false;
            }
            if (!file_put_contents($fn, $php)) {
                error_log("Can not include saved temp php code from {$fn}, you should add {$tmpDir} into open_basedir!!\n");
                return false;
            }
            $phpfunc = (include $fn);
            if ($delete) {
                unlink($fn);
            }
            return $phpfunc;
        }
        return include 'data://text/plain,' . urlencode($php);
    }

Usage Example

 /**
  * @dataProvider issueProvider
  */
 public function testIssues($issue)
 {
     global $tmpdir;
     $php = LightnCandy::compile($issue['template'], isset($issue['options']) ? $issue['options'] : null);
     $context = LightnCandy::getContext();
     $parsed = print_r(LightnCandy::$lastParsed, true);
     if (count($context['error'])) {
         $this->fail('Compile failed due to:' . print_r($context['error'], true) . "\nPARSED: {$parsed}");
     }
     $renderer = LightnCandy::prepare($php);
     $this->assertEquals($issue['expected'], $renderer($issue['data'], array('debug' => $issue['debug'])), "PHP CODE:\n{$php}\n{$parsed}");
 }
All Usage Examples Of LightnCandy\LightnCandy::prepare