-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTemplate.php
107 lines (84 loc) · 3.02 KB
/
Template.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
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace Core;
class Template
{
public static string $file_prefix = "Templates/";
public static string $resource_prefix = "Resources/";
private string $file = "";
use TemplateUtils\TraitFileProcessing;
public function __construct(string $file, Request $req = null)
{
$this->setFile($file);
if($req != null)
$this->setRequest($req);
}
public function setFile(string $file)
{
$this->file = self::$file_prefix . $file;
if (!file_exists($this->file))
throw new Exception("{$this->file} do not exist.");
}
public function run(Request $req = null): string
{
if($req != null)
$this->setRequest($req);
return $this->processFile($this->file);
}
/*
private function processFile(string $file): string
{
if (!file_exists($file)){
throw new Exception("Template $file do not exist.");
}
$output = file_get_contents($file);
do {
$output = $this->insertVariables($output);
$output = $this->insertFiles($output);
preg_match_all('/\$\{(.*)\}/', $output, $commands);
} while(count($commands[0]) > 0);
return $output;
}
*/
private function insertVariables(string $input): string
{
$commands = [];
preg_match_all('/\$\{([^{}:]*)\}/', $input, $commands);
foreach ($commands[1] as $i => $command){
$default = "\${$command}";
if (strpos($command, '=')){
$default = implode('=', array_slice(explode('=', $command), 1));
}
$command = explode('=', $command)[0];
$value = $this->variables[$command] ?? $default;
$input = str_replace($commands[0][$i], $value, $input);
}
return $input;
}
private function insertFiles(string $input): string
{
$commands = [];
preg_match_all('/\$\{([^{}]*)\}/', $input, $commands);
foreach ($commands[1] as $i => $command){
if (strpos($command, "include:") === 0 ||
strpos($command, "parse:") === 0){
$raw = str_replace(["include:", "parse:"], "", $command);
$subfile = $this->processFile("Templates/" . $raw);
$input = str_replace($commands[0][$i], $subfile, $input);
}
if (strpos($command, "resource:") === 0 ||
strpos($command, "path:") === 0){
$raw = str_replace(["resoure:", "path:"], "", $command);
$path = $this->request->path();
$prefix = str_repeat("../", max(count($path) - 1, 0));
$full_path = $prefix . "Resources/" . $raw;
$input = str_replace($commands[0][$i], $full_path, $input);
}
}
return $input;
}
}