-
-
Notifications
You must be signed in to change notification settings - Fork 167
Expand file tree
/
Copy pathEngine.php
More file actions
61 lines (49 loc) · 1.88 KB
/
Engine.php
File metadata and controls
61 lines (49 loc) · 1.88 KB
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
<?php
declare(strict_types=1);
namespace Safe\Templating;
use Safe\Templating\Exception\InvalidPlaceholderException;
use Safe\Templating\Exception\TemplateNotFoundException;
use Safe\Templating\Exception\TemplatingException;
use Safe\Templating\Exception\UnreadableTemplateException;
use Symfony\Component\Finder\Finder;
final class Engine
{
/**
* @var string[] $templates
*/
private array $templates;
public function __construct()
{
$finder = Finder::create()->files()->name('*.php.tpl')->in(self::basePath());
$this->templates = array_map(fn(\SplFileInfo $file) => str_replace(self::basePath() . '/', '', $file->getRealPath()), \iterator_to_array($finder->getIterator()));
}
/**
* @param array<string, string> $context
*
* @throws TemplatingException
*/
public function generate(string $template, array $context = []): string
{
if (!$this->hasTemplate($template)) {
throw new TemplateNotFoundException(\sprintf('Template "%s" not found.', $template));
}
if (false === $content = file_get_contents(self::basePath() . '/' . $template)) {
throw new UnreadableTemplateException(\sprintf('Could not read template "%s".', $template));
}
foreach ($context as $placeholder => $replacement) {
if (!\is_string($replacement)) {
throw new InvalidPlaceholderException(\sprintf('Placeholder "%s" must be a string.', $placeholder));
}
$content = str_replace($placeholder, $replacement, $content);
}
return $content;
}
private function hasTemplate(string $name): bool
{
return 0 < \count(\array_filter($this->templates, static fn(string $template) => $template === $name));
}
private static function basePath(): string
{
return Filesystem::generatorDir().'/templates';
}
}