Passed
Branch v1.5.1 (9f4477)
by Wanderson
01:49
created

Template::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Win\Common;
4
5
use Win\Application;
6
7
/**
8
 * Templates em .PHTML
9
 * Ver arquivos em: "templates/"
10
 */
11
class Template
12
{
13
	public static $dir = 'templates';
14
	public Application $app;
15
16
	/**
17
	 * Endereço completo do arquivo .phtml
18
	 * @var string
19
	 */
20
	protected string $file;
21
22
	protected $data = [];
23
24
	private ?string $layout = null;
25
26
	/**
27
	 * Cria um template com base no arquivo escolhido
28
	 * @param string $file Nome do arquivo
29
	 * @param mixed[] $data Array de variáveis
30
	 * @param string $layout Layout
31
	 */
32
	public function __construct($file, $data = [], $layout = null)
33
	{
34
		$this->app = Application::app();
35
		$this->file = BASE_PATH . '/' . static::$dir . "/$file.phtml";
36
		$this->data = $data;
37
		$this->layout = $layout;
38
	}
39
40
	/**
41
	 * Carrega e retorna o output
42
	 * @return string
43
	 */
44
	public function __toString()
45
	{
46
		return (string) $this->toHtml();
47
	}
48
49
	/**
50
	 * Retorna uma variável
51
	 * @param string $name
52
	 * @return mixed|null
53
	 */
54
	public function getData($name)
55
	{
56
		if (key_exists($name, $this->data)) {
57
			return $this->data[$name];
58
		}
59
60
		return null;
61
	}
62
63
	/**
64
	 * Retorna TRUE se o template existe
65
	 * @return bool
66
	 */
67
	public function exists()
68
	{
69
		return file_exists($this->file);
70
	}
71
72
	/**
73
	 * Carrega e retorna o output
74
	 * @return string
75
	 */
76
	public function toHtml()
77
	{
78
		if ($this->layout) {
79
			return new Template($this->layout, ['content' => $this]);
80
		}
81
82
		ob_start();
83
		$this->load();
84
		return ob_get_clean();
85
	}
86
87
	/**
88
	 * Carrega e exibe o conteúdo do template
89
	 */
90
	public function load()
91
	{
92
		if (isset($this->file) && $this->exists()) {
93
			extract($this->data);
94
			include $this->file;
95
		}
96
	}
97
}
98