Transform template file into a php file.

@return void
@throws \Exception
327943
protected function compile()
    {
        $templateContent = file_get_contents($this->file);

        foreach ($this->patternCollection as $pattern) {
            $templateContent = $pattern->setContent($templateContent)
                ->render();
        }

        if (false === file_put_contents($this->fileCompiled, $templateContent)) {
            throw new \Exception('Cannot write compiled template file!');
        }
    }
116398
private function runTemplate()
    {
        if (!isset(Template::$complieCache[$this->tplId])) {
            $file = Utils::path($this->sdopx->compileDir, $this->tplId . '.php');
            if (file_exists($file)) {
                Template::$complieCache[$this->tplId] = require($file);
            }
        }
        if (isset(Template::$complieCache[$this->tplId])) {
            $_property = &Template::$complieCache[$this->tplId];
            if (!$this->sdopx->compileCheck || $this->validProperties($_property)) {
                return $this->run($_property['runFunc']);
            } else {
                unset(Template::$complieCache[$this->tplId]);
            }
        }
        return $this->compileAndRunTemplate();
    }
415058
private function renderViewFile()
    {
        try {

            ob_start();
            extract($this->view_data);

            /** @noinspection PhpIncludeInspection */
            include($this->view_file);

            return trim(ob_get_clean(), "\n");

        } catch (\Exception $e) {

            ob_end_clean();
            throw $e;
        }
    }
877247
protected function exportInternal()
    {
        // Read the linked TypoScript
        if ($this->config !== null) {
            $templateFile = GeneralUtility::getFileAbsFileName($this->config);
            if (!strlen($templateFile) || !is_file($templateFile)) {
                throw new \RuntimeException(sprintf('Invalid template file "%s"', $templateFile), 1481552328);
            }
            $this->template = file_get_contents($templateFile);
        }

        return parent::exportInternal();
    }
90908
protected function display()
    {
        foreach ($this->values as $key => $value) {
            $$key = $value;
        }

        require $this->TemplateDir.'/'.$this->templateFile;
    }
702323
private function make_data($file)
  {
    if (!array_key_exists('template', $file)) {
      throw new Exception('x> Current page: ' . $file['title'] . ' does not have a template.');
    }

    $t = Application::templates()->template($file['template']);

    $tmpl = $file;
    $tmpl['slug'] = $this->make_slug($file, $tmpl);

    $data_folder = Application::data_folder();
    $template_name = $data_folder . '/templates/' . $t;
    $content_template = $data_folder . '/' . $file['content'];

    $render_content_with = Application::renders()->select($content_template);
    $render_with = Application::renders()->select($template_name);

    $tmpl['html'] = $render_with->render($template_name, [
      'content' => $render_content_with->render($content_template, [
        'post'=> $file,
      ]),
      'post'=> $file,
    ]);

    if ($this->is_index($file['file'])) {
      $this->log_current_page('index', '');
    } else {
      $this->log_current_page($file['title'], $tmpl['slug']);
    }

    return $tmpl;
  }
186002
public function parse()
    {
        if (!is_file($this->file)) {
            throw new \Exception(sprintf(
                'Template "%s" file doesn\'t exist!', $this->file
            ));
        }

        $fp = fopen($this->file, 'r');

        $lineCount       = 0;
        $nextToken       = '';
        $block           = '';
        $currentValue    = '';
        $stringComposing = false;
        $skipMultilineComment = false;

        while (($line = fgets($fp)) !== false) {
            $lineCount++;

            if ($stringComposing) {
                if (substr(ltrim($line), 0, 3) === '>>>') {
                    $this->blocks[$block][$name] = trim($value);
                    //$block = '';
                    $value = '';
                    $stringComposing = false;
                } else {
                    // $line = trim($line);
//                     if (substr($value, -1) != '>' && ! empty($line)) {
//                         $line = " " . $line;
//                     }

                    //$value .= substr($value, -1) == '>' ? trim($line) : " " . trim($line);
                    $value .= $line;
                }

                continue;
            }

            $line = trim($line);

            if (substr($line, 0, 1) === '#' || $line === '' || substr($line, 0, 2) === '//') {
                continue; // skip single comments or empty lines
            } elseif (substr($line, 0, 2) === '/*') { // start multiline comment
                if (strpos($line, '*/') === false) {
                    $skipMultilineComment = true; // activate multiline comments skipping
                } else {
                    continue; // just skip this line, it has the form: /* ... */
                }
            } elseif (strpos($line, '*/') !== false) { // end multiline comment
                $skipMultilineComment = false;
                continue; // just skip the end multiline comment
            }

            if ($skipMultilineComment) {
                continue; //skip multiline comments segment
            }

            $kwPattern = '^@(?<keyword>\w+)';

            if (! preg_match('/'.$kwPattern.'.*/', $line, $matches)) {
                throw new \Exception(sprintf(
                    'Parse Error: Unknow keyword, lines must starts with a valid keyword, near: %s, on line %s',
                    $line, $lineCount
                ));
            }
            //var_dump($matches);
            $keyword = $matches['keyword'];

            switch ($keyword) {
                case Parser::T_DEF:
                    $pattern = '/'.$kwPattern.'\s+(?<type>[\w]+)\s+(?<name>[\w.]+)\s+(?<value>.+)/';

                    if (!preg_match($pattern, $line, $matches)) {
                        throw new \Exception(sprintf(
                            "Syntax Error: near: '%s', on line %s.\n" .
                            "Syntax should be: @def <type> <name> <value>",
                            $line, $lineCount
                        ));
                    }

                    $keyword = $matches['keyword'];
                    $type    = $matches['type'];
                    $name    = $matches['name'];
                    $value   = $matches['value'];

                    $tmp     = explode('.', $name);
                    $defName = $tmp[0];
                    $defProp = isset($tmp[1]) ? $tmp[1] : '';

                    switch ($type) {
                        case Parser::T_GLOBAL:
                        case Parser::T_ITERATOR:
                        case Parser::T_SETCONF:
                            if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') {
                                $value = trim($value, '"');
                            } elseif (substr($value, 0, 1) == "'" && substr($value, -1) == "'") {
                                $value = trim($value, "'");
                            }

                            if ($value === '\n' || $value === '\r\n') {
                                $value = "\n";
                            }

                            $value = self::castValue($value);

                            if (empty($defProp)) {
                                $this->defs[$type][$defName] = $value;
                            } else {
                                $this->defs[$type][$defName][$defProp] = $value;
                            }
                            break;
                        default:
                            throw new \Exception(sprintf(
                                'Parse Error: unknow definition type: "%s" on line %s.', $type, $lineCount
                            ));
                    }
                    break;
                case Parser::T_BLOCK:
                    $pattern = '/'.$kwPattern.'\s+(?<block>[\w]+)/';

                    if (!preg_match($pattern, $line, $matches)) {
                        throw new Exception(sprintf(
                            "Parse Error: Syntax error near: %s, on line %s.\n." .
                            "Syntax should be: @def <type> <name> <value>",
                            substr($line, 0, 20).'...', $lineCount
                        ));
                    }
                    //var_dump($matches);

                    $block = $matches['block'];

                    if (!empty($nextToken)) {
                        throw new \Exception(sprintf(
                            'Parse Error: expected: @"%s", given: @"%s"', $nextToken, Parser::T_BLOCK
                        ));
                    }

                    $nextToken = Parser::T_END;
                    break;
                case Parser::T_END:
                    if (empty($nextToken)) {
                        throw new \Exception(sprintf(
                            'Parse Error: close keyword: @"%s" given, but any block was started.', Parser::T_BLOCK
                        ));
                    }

                    if ($nextToken !== Parser::T_END) {
                        throw new \Exception(sprintf(
                            'Parse Error: expected: @"%s", given: @"%s"', $nextToken, Parser::T_END
                        ));
                    }

                    $nextToken = '';
                    break;
                case Parser::T_VAR:
                    $pattern = '/'.$kwPattern.'\s+(?<name>[\w]+)\s+(?<value>.+)/';

                    if (!preg_match($pattern, $line, $matches)) {
                        throw new Exception(sprintf(
                            "Parse Error: Syntax error near: %s, on line %s.\n." .
                            "Syntax should be: @var <name> <value>\n or \n" .
                            "@var <name> <<<\nsome large string\nmultiline...\n>>>\n\n",
                            substr($line, 0, 20).'...', $lineCount
                        ));
                    }
                    //print_r($matches);
                    $keyword = $matches['keyword'];
                    $name    = $matches['name'];
                    $value   = $matches['value'];

                    if (substr($value, 0, 3) === '<<<' && $value !== '<<<') {
                        throw new \Exception(sprintf(
                            "Syntax Error: multiline string must starts on new line after open braces <<<\n" .
                            "near: '%s', on line %s", $line, $lineCount
                        ));
                    }

                    if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') {
                        $value = trim($value, '"');
                    } elseif (substr($value, 0, 1) == "'" && substr($value, -1) == "'") {
                        $value = trim($value, "'");
                    }

                    if ($value !== '<<<') {
                        $this->blocks[$block][$name] = self::castValue($value);
                    } else {
                        $value = '';
                        $stringComposing = true;
                    }
                    break;
                default:
                    throw new \Exception(sprintf(
                        'Parse Error: Unknown definition type: %s, on line %s', $type, $lineCount
                    ));
            }

        }

        if ($stringComposing) {
            throw new \Exception(sprintf(
                "Parse Error: Multiline string closing braces are missing '>>>',\nfor @block: '%s', @var: '%s' " .
                "until end of file.", $block, $name
            ));
        }
    }
98909
public function render()
    {
        $source = $this->getOption('templateSource');
        $templatePathAndFilename = $this->getOption('templatePathAndFilename');
        if ($templatePathAndFilename !== null) {
            $source = file_get_contents($templatePathAndFilename);
        }

        return preg_replace_callback('/\{([a-zA-Z0-9\-_.]+)\}/', function ($matches) {
            return ObjectAccess::getPropertyPath($this->variables, $matches[1]);
        }, $source);
    }
681617
public function GetTemplateFiles()
	{
		$files = array();
		
		list($nothing,$data) = explode("[files]", $this->GetConfigFileContents(),2);
		
		if ($data)
		{
			$lines = explode("\n",$data);
			
			foreach ($lines as $line)
			{
				if ($line) $files[] = new TemplateFile($line);
			}
		}
		
		return $files;
	}
1103843
public function draw()
    {
        $file = Application::current()->getDirectory();
        $file .= "views/{$this->templateName}.";
        $file .= self::$extension;

        if (!file_exists($file)) {
            throw new Exception("Template file not found: $file");
        }

        return $this->templateEngine->draw(
            $file, $this->data
        );
    }
674799
public function output()
    {
        if (!file_exists($this->_file))
            throw new RuntimeException(
                "Error loading template file: $this->_file.", 
                1
            );

        $output = file_get_contents($this->_file);
        
        foreach ($this->_vars as $key => $value) {
            $tagToReplace = "[@$key]";
            $output = str_replace($tagToReplace, $value, $output);
        }

        return $output;
    }
380527
public function render(string $file = null): string
    {
        if ($file) {
            $this->setFile($file);
        }

        if (empty($this->file)) {
            throw new \Exception('You must set the file to use within your view before rendering');
        }

        return $this->capture($this->file, $this->data, static::$globalData);
    }
87954
protected function prepare()
    {
        // Set data into dataDocument structure;
        if (is_array($this->data)) {
            foreach ($this->data as $key => $value) {
                $this->addData($key, $value);
            }
        }

     Logger::get()->debug("Response data:\n" . $this->dataDocument->toString(false));

        // Merge data with template.
        $this->document = $this->dataDocument->transform($this->getTemplate());
    }
350983
public function dump()
    {
        if (empty($this->files)) {
            return;
        }

        $buffer = <<<'PHP'
<?php

$runonce = function(array $files, $delete = false) {
    foreach ($files as $file) {
        try {
            include $file;
        } catch (\Exception $e) {}

        $relpath = str_replace(TL_ROOT . DIRECTORY_SEPARATOR, '', $file);

        if ($delete && !unlink($file)) {
            throw new \Exception(
                'The file ' . $relpath . ' cannot be deleted. ' .
                'Please remove the file manually and correct the file permission settings on your server.'
            );
        }
    }
};

PHP;

        if (file_exists($this->targetFile)) {
            if (!is_writable($this->targetFile) || !is_file($this->targetFile)) {
                throw new \RuntimeException(
                    sprintf('Runonce file "%s" exists but is not writable.', $this->targetFile)
                );
            }

            $current = str_replace('.php', '_'.substr(md5(mt_rand()), 0, 8).'.php', $this->targetFile);
            $this->filesystem->rename($this->targetFile, $current);

            $buffer .= "\n\$runonce(array('" . $current . "'), true);\n";
        }

        $buffer .= "\n\$runonce(" . var_export(array_unique($this->files), true) . ");\n";

        $this->filesystem->ensureDirectoryExists(dirname($this->targetFile));

        if (false === file_put_contents($this->targetFile, $buffer)) {
            throw new \RuntimeException(sprintf('Could not write runonce file to "%s"', $this->targetFile));
        }

        $this->files = [];
    }
375460
function toHtml()
    {
        $e = $this->e;

        try {
            $renderer = new RendererPhp();
            return $renderer->capture(
                __DIR__ . '/../.error.page.php'
                , array('exception' => $e)
            );
        } catch(\Exception $ve) {
            ## throw exception if can't render template
            throw $e;
        }
    }
663844
private function makeTpl() {
		$this->localTpl = rtrim($this->localTpl, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
		$this->wipe[] = $output = self::path(sys_get_temp_dir()) . 'twigjs' . time() . DIRECTORY_SEPARATOR;
		self::readyDir($output);
		
		$data = array();
		
		foreach (self::rglob($this->localTpl . '*.twig') as $file) {
			$id = substr($file, strlen($this->localTpl));
			$data[ $id ] = file_get_contents($file);
		}
		
		file_put_contents($output . 'tpl.js', 'var templates = '. json_encode($data) .';');

		$this->addLocalStatic('js', $output);
		//$this->addCopy($this->localTpl);
		
		return $this;
	}
1182335
protected function loadTemplates()
    {
        if ($this->templates === null) {
            $this->templates = array();
            $data = file_get_contents($this->fileName, false, null, $this->offset);
            foreach (preg_split("/^@@(?= [\w\d\.]+$)/m", $data, -1) as $chunk) {
                if (trim($chunk)) {
                    list($name, $content)         = explode("\n", $chunk, 2);
                    $this->templates[trim($name)] = trim($content);
                }
            }
        }
    }