/
Renderer.php
143 lines (115 loc) · 3.14 KB
/
Renderer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
<?php
namespace Rougin\Slytherin\Template;
/**
* Renderer
*
* A simple implementation of a template renderer.
*
* @package Slytherin
*
* @author Rougin Gutib <rougingutib@gmail.com>
*/
class Renderer implements RendererInterface
{
/**
* @var string[]
*/
protected $paths = array();
/**
* Initializes the renderer instance.
*
* @param string|string[] $paths
*/
public function __construct($paths)
{
$this->paths = (array) $paths;
}
/**
* Renders a file from a specified template.
*
* @param string $template
* @param array<string, mixed> $data
*
* @return string
*
* @throws \InvalidArgumentException
*/
public function render($template, array $data = array())
{
list($file, $name) = array(null, str_replace('.', '/', $template));
foreach ((array) $this->paths as $key => $path)
{
$files = (array) $this->files($path);
$item = $this->check($files, $path, $key, "$name.php");
if ($item !== null)
{
$file = $item;
}
}
if (! is_null($file))
{
return $this->extract($file, $data);
}
$message = 'Template file "' . $name . '" not found.';
throw new \InvalidArgumentException((string) $message);
}
/**
* Checks if the specified file exists.
*
* @param array<string, string> $files
* @param string $path
* @param string $source
* @param string $template
*
* @return string|null
*/
protected function check(array $files, $path, $source, $template)
{
$file = null;
foreach ((array) $files as $key => $value)
{
$filepath = str_replace($path, $source, $value);
$filepath = str_replace('\\', '/', (string) $filepath);
/** @var string */
$filepath = preg_replace('/^\d\//i', '', $filepath);
$exists = (string) $filepath === $template;
$lowercase = strtolower($filepath) === $template;
if ($exists || $lowercase)
{
$file = $value;
}
}
return $file;
}
/**
* Extracts the contents of the specified file.
*
* @param string $filepath
* @param array<string, mixed> $data
*
* @return string
*/
protected function extract($filepath, array $data)
{
extract($data);
ob_start();
include $filepath;
$contents = ob_get_contents();
ob_end_clean();
return $contents ?: '';
}
/**
* Returns an array of filepaths from a specified directory.
*
* @param string $path
*
* @return string[]
*/
protected function files($path)
{
$directory = new \RecursiveDirectoryIterator($path);
$iterator = new \RecursiveIteratorIterator($directory);
$regex = new \RegexIterator($iterator, '/^.+\.php$/i', 1);
return (array) array_keys(iterator_to_array($regex));
}
}