<?php
namespace Template;

use Utils\Helper;

final class Twig {
	private $data = array();

	public function set($key, $value) {
		$this->data[$key] = $value;
	}

	public function render($template, $cache = false) {
		// specify where to look for templates
		$loader = new \Twig\Loader\FilesystemLoader(DIR_TEMPLATE);

		// initialize Twig environment
		$config = array('autoescape' => false);

		if ($cache) {
			$config['cache'] = DIR_CACHE;
		}

		$twig = new \Twig\Environment($loader, $config);

		try {
		    $this->data['helper'] = Helper::getSingleton();
            //自定义函数
            $function = new \Twig\TwigFunction('template',function($file,$data = []) use($loader,$twig){
                $theme = config('config_theme') == 'default' ? config('theme_default_directory') : config('config_theme');
                $twig_path = $theme.'/template/'.$file.'.twig';
                $file_path = DIR_TEMPLATE.$twig_path;
                $content =  file_get_contents($file_path);
                if($content) {
                    //$loader->setTemplate($file . '.twig', $content);
                    $twig->render($twig_path, $data);
                    return $twig_path;
                }
                return '';
            });
            $twig->addFunction($function);
			// load template
			//$template = $this->twig->loadTemplate($template . '.twig');
            $data = $twig->render($template . '.twig', $this->data);
            return $data;
			//return $template->render($this->data);
		} catch (Exception $e) {
			trigger_error('Error: Could not load template ' . $template . '!');
			exit();
		}
	}
}
