1
|
|
|
<?php |
2
|
|
|
namespace Yoanm\DefaultPhpRepository\Helper; |
3
|
|
|
|
4
|
|
|
use Symfony\Component\Filesystem\Filesystem; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* Class TemplateFileProcessor |
8
|
|
|
*/ |
9
|
|
|
class TemplateHelper |
10
|
|
|
{ |
11
|
|
|
/** @var array */ |
12
|
|
|
private $variableList = []; |
13
|
|
|
/** @var string[] */ |
14
|
|
|
private $variableNameList = []; |
15
|
|
|
/** @var string */ |
16
|
|
|
private $filenameResolverRegexp; |
17
|
|
|
/** @var Filesystem */ |
18
|
|
|
private $fs; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @param array $variableList |
22
|
|
|
* @param array $extraTemplatePath |
23
|
|
|
*/ |
24
|
|
|
public function __construct(array $variableList, array $extraTemplatePath = []) |
25
|
|
|
{ |
26
|
|
|
$this->variableList = $variableList; |
27
|
|
|
foreach ($this->variableList as $variableId => $variableValue) { |
28
|
|
|
$variableId = sprintf('%%%s%%', $variableId); |
29
|
|
|
$this->variableNameList[$variableId] = $variableId; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
foreach ($extraTemplatePath as $extraKey => $extraValue) { |
33
|
|
|
$variableId = sprintf('%%%s%%', $extraKey); |
34
|
|
|
$this->variableNameList[$variableId] = $variableId; |
35
|
|
|
$this->variableList[$variableId] = $this->loadTemplate($extraValue); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
// compile this regexp at startup (no need to to it each time) |
39
|
|
|
$this->filenameResolverRegexp = '#/?(?:[^/]+/)*([^/]+)\.tmpl$#'; |
40
|
|
|
|
41
|
|
|
$this->fs = new Filesystem(); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @param string $templateFilePath |
46
|
|
|
* @param string $outputFilePath |
47
|
|
|
*/ |
48
|
|
|
public function dumpTemplate($templateFilePath, $outputFilePath) |
49
|
|
|
{ |
50
|
|
|
$this->fs->dumpFile($outputFilePath, $this->loadTemplate($templateFilePath)); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @param string $templateFilePath |
55
|
|
|
* @param string $outputDir |
56
|
|
|
* |
57
|
|
|
* @return string |
58
|
|
|
*/ |
59
|
|
|
public function resolveOutputFilePath($templateFilePath, $outputDir) |
60
|
|
|
{ |
61
|
|
|
return sprintf( |
62
|
|
|
'%s%s', |
63
|
|
|
PathHelper::appendPathSeparator($outputDir), |
64
|
|
|
$this->resolveOutputFilename($templateFilePath) |
65
|
|
|
); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @param string $templateFilePath |
70
|
|
|
* |
71
|
|
|
* @return string |
72
|
|
|
*/ |
73
|
|
|
public function resolveOutputFilename($templateFilePath) |
74
|
|
|
{ |
75
|
|
|
return preg_replace($this->filenameResolverRegexp, '\1', $templateFilePath); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* @param string $templateFilePath |
80
|
|
|
* |
81
|
|
|
* @return string file content |
82
|
|
|
*/ |
83
|
|
|
public function loadTemplate($templateFilePath) |
84
|
|
|
{ |
85
|
|
|
return str_replace($this->variableNameList, $this->variableList, file_get_contents($templateFilePath)); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|