Passed
Push — master ( dfeadf...0d8182 )
by Jean-Christophe
04:51
created

Twig::render()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 3
crap 2
1
<?php
2
3
namespace Ubiquity\views\engine;
4
5
use Ubiquity\controllers\Startup;
6
use Ubiquity\controllers\Router;
7
use Ubiquity\cache\CacheManager;
8
use Ubiquity\core\Framework;
9
use Ubiquity\utils\base\UFileSystem;
10
use Ubiquity\translation\TranslatorManager;
11
12
/**
13
 * Ubiquity Twig template engine
14
 * @author jcheron <[email protected]>
15
 * @version 1.0.1
16
 */
17
class Twig extends TemplateEngine {
18
	private $twig;
19
20 20
	public function __construct($options=array()) {
21 20
		$loader=new \Twig_Loader_Filesystem(\ROOT . \DS . "views".\DS);
22 20
		$loader->addPath(implode(\DS,[Startup::getFrameworkDir(),"..","core","views"]).\DS,"framework");
23 20
		if(isset($options["cache"]) && $options["cache"]===true)
24
			$options["cache"]=CacheManager::getCacheSubDirectory("views");
25 20
		$this->twig=new \Twig_Environment($loader, $options);
26
27
		$function=new \Twig_SimpleFunction('path', function ($name,$params=[],$absolute=false) {
28 2
			return Router::path($name,$params,$absolute);
29 20
		});
30 20
		$this->twig->addFunction($function);
31
		$function=new \Twig_SimpleFunction('url', function ($name,$params) {
32
			return Router::url($name,$params);
33 20
		});
34 20
		$this->twig->addFunction($function);
35
		
36
		$function=new \Twig_SimpleFunction('t', function ($context,$id, array $parameters = array(), $domain = null, $locale = null) {
37
			$trans=TranslatorManager::trans($id,$parameters,$domain,$locale);
38
			return $this->twig->createTemplate($trans)->render($context);
39 20
		},['needs_context' => true]);
40 20
		$this->twig->addFunction($function);
41
		
42
		$test=new \Twig_SimpleTest('instanceOf', function($var,$class){ 
43
			return  $var instanceof $class;
44 20
		});
45 20
		$this->twig->addTest($test);
46 20
		$this->twig->addGlobal("app", new Framework());
47 20
	}
48
49
	/*
50
	 * (non-PHPdoc)
51
	 * @see TemplateEngine::render()
52
	 */
53 15
	public function render($viewName, $pData, $asString) {
54 15
		$render=$this->twig->render($viewName, $pData);
55 15
		if ($asString) {
56 1
			return $render;
57
		} else{
58 15
			echo $render;
59
		}
60 15
	}
61
62
	public function getBlockNames($templateName) {
63
		return $this->twig->load($templateName)->getBlockNames();
64
	}
65
	
66
	public function getCode($templateName){
67
		return UFileSystem::load($this->twig->load($templateName)->getSourceContext()->getPath());
68
	}
69
70
}
71