Completed
Push — master ( 0db593...5f0535 )
by Jean-Christophe
01:58
created

View   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 15
lcom 1
cbo 2
dl 0
loc 69
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A includeFileAsString() 0 5 1
A setVar() 0 4 1
A setVars() 0 7 2
A getVar() 0 5 2
C render() 0 24 7
A getBlockNames() 0 4 1
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 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
		$ext=\pathinfo($viewName, PATHINFO_EXTENSION);
56
		if ($ext === null)
57
			$viewName=$viewName . ".php";
58
		$data=$this->vars;
59
		if (!UString::endswith($viewName, ".php") && @$config["templateEngine"] instanceof TemplateEngine) {
60
			return $config["templateEngine"]->render($viewName, $data, $asString);
61
		}
62
63
		if (is_array($data)) {
64
			extract($data);
65
		}
66
		$fileName=ROOT . DS . "views/" . $viewName;
67
		if(file_exists($fileName)){
68
			if ($asString) {
69
				return $this->includeFileAsString($fileName);
70
			} else {
71
				include ($fileName);
72
			}
73
		}else{
74
			throw new \Exception("View {$viewName} not found!");
75
		}
76
	}
77
	
78
	public function getBlockNames($templateName){
79
		$config=Startup::getConfig();
80
		return $config["templateEngine"]->getBlockNames($templateName);
81
	}
82
}
83