Completed
Push — master ( 4e6026...e0b9fa )
by Jean-Christophe
01:30
created

View::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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