Passed
Pull Request — master (#22)
by Wanderson
02:51
created

Template::toHtml()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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