This repository was archived by the owner on Feb 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.php
80 lines (68 loc) · 2.03 KB
/
parser.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
<?php
/**
* HTML Template Parser
*
* Uses type hinting introduced in PHP 7
*
* @author Hans Erik Jepsen <hanserikjepsen@hotmail.com>
*/
class Parser {
/**
* Contains the template.
*
* @var string
*/
private $tempalte;
/**
* Takes a template and an array with the placeholders and the value to replace them with
*
* @param string $view The path to the file containing the HTML template.
* @param array $data The array containing the placeholders and replacement values.
*/
function __construct(string $view, array $data)
{
if (empty($view))
{
throw new Exception('View not found.');
}
if (empty($data))
{
throw new Exception('No data passed.');
}
$this->template = file_get_contents($view);
foreach ($data as $key => $value)
{
$this->replace($key,$value);
}
}
/**
* Replaces the placeholders in the template with the values from the data array.
*
* @param string $key The key from the data array passed to the constructor.
* @param string $value The value from the data array passed to the constructor.
*
* @return true Returns true when the script has finished running.
*/
private function replace(string $key, string $value) : true
{
if (empty($key) || empty($value))
{
throw new Exception('A key or value is missing.');
}
$this->template = preg_replace('/{{ '.$key.' }}/', $value, $this->template);
return true;
}
/**
* Returns the template property.
*
* @return string The finished view with all placeholders replaced is returned for rendering.
*/
public function render() : string
{
if (empty($this->template))
{
throw new Exception('The template was not set, thus could not be rendered.');
}
return $this->template;
}
}