Passed
Branch v1.6.0 (c77ef3)
by Wanderson
01:54
created

Template::include()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 4
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 5
rs 10
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
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 get($name)
55
	{
56
		return $this->data[$name] ?? null;
57
	}
58
59
	/**
60
	 * Retorna TRUE se o template existe
61
	 * @return bool
62
	 */
63
	public function exists()
64
	{
65
		return file_exists($this->file);
66
	}
67
68
	/**
69
	 * Carrega e retorna o output
70
	 * @return string
71
	 */
72
	public function toHtml()
73
	{
74
		ob_start();
75
		$this->include();
76
		$content = ob_get_clean();
77
78
		if ($this->layout) {
79
			return new self($this->layout, ['content' => $content]);
80
		}
81
		return $content;
82
	}
83
84
	/**
85
	 * Carrega e exibe o conteúdo do template
86
	 */
87
	protected function include()
88
	{
89
		if (isset($this->file) && $this->exists()) {
90
			extract($this->data);
91
			include $this->file;
92
		}
93
	}
94
}
95