-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathPHPTemplateEngine.php
56 lines (47 loc) · 1.62 KB
/
PHPTemplateEngine.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
<?php
declare(strict_types=1);
namespace Flasher\Prime\Template;
/**
* PHPTemplateEngine - Simple PHP-based template rendering engine.
*
* This implementation provides a straightforward template rendering mechanism using
* native PHP as the template language. It works by including PHP files and extracting
* context variables into the template's scope.
*
* Design patterns:
* - Strategy: Implements a specific template rendering strategy
* - Output Capture: Uses output buffering to capture rendered content
*
* Security considerations:
* - Context variables are extracted with EXTR_SKIP flag to prevent variable overwriting
* - Template files must exist and be readable
*/
final class PHPTemplateEngine implements TemplateEngineInterface
{
/**
* {@inheritdoc}
*
* This implementation:
* 1. Verifies the template file exists and is readable
* 2. Starts output buffering
* 3. Extracts context variables into the current scope
* 4. Includes the template file
* 5. Captures and returns the output
*
* @throws \InvalidArgumentException If the template file doesn't exist or isn't readable
*/
public function render(string $name, array $context = []): string
{
if (!file_exists($name) || !is_readable($name)) {
throw new \InvalidArgumentException(\sprintf('Template file "%s" does not exist or is not readable.', $name));
}
ob_start();
extract($context, \EXTR_SKIP);
include $name;
$output = ob_get_clean();
if (false === $output) {
return '';
}
return ltrim($output);
}
}