Passed
Push — master ( 4d0f3d...b95030 )
by Jean-Christophe
02:31
created

View::getVar()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 3
ccs 0
cts 3
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Ubiquity\views;
4
5
use Ubiquity\utils\base\UString;
6
use Ubiquity\views\engine\TemplateEngine;
7
use Ubiquity\controllers\Startup;
8
9
/**
10
 * Represents a view
11
 * @author jcheron <[email protected]>
12
 * @version 1.0.2
13
 *
14
 */
15
class View {
16
	private $vars;
17
18 2
	public function __construct() {
19 2
		$this->vars=array ();
20 2
	}
21
22
	protected function includeFileAsString($filename) {
23
		\ob_start();
24
		include ($filename);
25
		return \ob_get_clean();
26
	}
27
28
	public function setVar($name, $value) {
29
		$this->vars[$name]=$value;
30
		return $this;
31
	}
32
33
	public function setVars($vars) {
34
		if (\is_array($vars))
35
			$this->vars=\array_merge($this->vars, $vars);
36
		else
37
			$this->vars=$vars;
38
		return $this;
39
	}
40
41
	public function getVar($name) {
42
		if (\array_key_exists($name, $this->vars)) {
43
			return $this->vars[$name];
44
		}
45
	}
46
47
	/**
48
	 * affiche la vue $viewName
49
	 * @param string $viewName nom de la vue à charger
50
	 * @param boolean $asString Si vrai, la vue n'est pas affichée mais retournée sous forme de chaîne (utilisable dans une variable)
51
	 * @throws \Exception
52
	 * @return string
53
	 */
54
	public function render($viewName, $asString=false) {
55
		$templateEngine=Startup::$templateEngine;
56
		$ext=\pathinfo($viewName, PATHINFO_EXTENSION);
57
		if ($ext === null)
58
			$viewName=$viewName . ".php";
59
		$data=$this->vars;
60
		if (!UString::endswith($viewName, ".php") && $templateEngine instanceof TemplateEngine) {
61
			return $templateEngine->render($viewName, $data, $asString);
62
		}
63
64
		if (is_array($data)) {
65
			extract($data);
66
		}
67
		$fileName=\ROOT . \DS . "views".\DS . $viewName;
68
		if(file_exists($fileName)){
69
			if ($asString) {
70
				return $this->includeFileAsString($fileName);
71
			} else {
72
				include ($fileName);
73
			}
74
		}else{
75
			throw new \Exception("View {$viewName} not found!");
76
		}
77
	}
78
	
79
	public function getBlockNames($templateName){
80
		return Startup::$templateEngine->getBlockNames($templateName);
81
	}
82
	
83
	public function getCode($templateName){
84
		return Startup::$templateEngine->getCode($templateName);
85
	}
86
}
87