/
Wrapper.php
85 lines (76 loc) · 2.78 KB
/
Wrapper.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
<?php
namespace Lucinda\Templating;
/**
* Reads templating tag in order to bind it to a view and compiles response
*/
class Wrapper
{
private string $templatesFolder;
private string $compilationsFolder;
private string $templatesExtension;
private string $tagLibFolder;
/**
* Calls for interpreting contents of <application> XML tag.
*
* @param \SimpleXMLElement $xml XML file holding compiler settings.
* @throws ConfigurationException If XML is improperly configured.
*/
public function __construct(\SimpleXMLElement $xml)
{
$this->readConfiguration($xml);
}
/**
* Reads XML then delegates to ViewLanguageAPI to compile a templated view recursively into a PHP file.
*
* @param \SimpleXMLElement $xml XML file holding compiler settings.
* @throws ConfigurationException If XML is improperly configured.
*/
private function readConfiguration(\SimpleXMLElement $xml): void
{
// parses XML
$xml = $xml->templating;
if (empty($xml)) {
throw new ConfigurationException("Tag 'templating' missing");
}
// gets settings from attributes
$this->compilationsFolder = (string) $xml["compilations_path"];
if (!$this->compilationsFolder) {
throw new ConfigurationException("Attribute 'compilations' is mandatory for 'templating' tag");
}
$this->tagLibFolder = (string) $xml["tags_path"];
$this->templatesFolder = (string) $xml["templates_path"];
$this->templatesExtension = (string) $xml["templates_extension"];
if (!$this->templatesExtension) {
$this->templatesExtension = "html";
}
}
/**
* Loads compilation file, binds it to data and returns HTML to be rendered
*
* @param string $viewFile View file location (without extension, optionally including views folder path)
* @param array $data
* @return string
* @throws ViewException If compilation failed due to a developer error.
*/
public function compile(string $viewFile, array $data): string
{
// gets view file
if ($this->templatesFolder && str_starts_with($viewFile, $this->templatesFolder)) {
$viewFile = substr($viewFile, strlen($this->templatesFolder)+1);
}
// compiles templates recursively into a single PHP file
$vlp = new ViewLanguageParser(
$this->templatesFolder,
$this->templatesExtension,
$this->compilationsFolder,
$this->tagLibFolder
);
$compilationFile = $vlp->compile($viewFile);
// compiles PHP file into HTML
ob_start();
include $compilationFile;
$output = ob_get_contents();
ob_end_clean();
return $output;
}
}