1 | <?php |
||||
2 | |||||
3 | namespace Helick\Blocks\Traits; |
||||
4 | |||||
5 | use Exception; |
||||
6 | use Helick\Blocks\Exceptions\BlockException; |
||||
7 | |||||
8 | trait Renderable |
||||
9 | { |
||||
10 | /** |
||||
11 | * Captures the output that is generated when a template is included. |
||||
12 | * This property is static to prevent object scope resolution. |
||||
13 | * |
||||
14 | * @param string $template |
||||
15 | * @param array $data |
||||
16 | * |
||||
17 | * @return string |
||||
18 | * |
||||
19 | * @throws Exception |
||||
20 | */ |
||||
21 | protected static function capture(string $template, array $data): string |
||||
22 | { |
||||
23 | extract($data, EXTR_SKIP); |
||||
24 | |||||
25 | ob_start(); |
||||
26 | |||||
27 | try { |
||||
28 | include $template; |
||||
29 | } catch (Exception $e) { |
||||
30 | ob_end_clean(); |
||||
31 | |||||
32 | throw $e; |
||||
33 | } |
||||
34 | |||||
35 | return ob_get_clean(); |
||||
36 | } |
||||
37 | |||||
38 | /** |
||||
39 | * Render the block. |
||||
40 | * |
||||
41 | * [!!] Global variables with the same key name as local variables will be |
||||
42 | * overwritten by the local variable. |
||||
43 | * |
||||
44 | * @param array $fields |
||||
45 | * @param array $attributes |
||||
46 | * @param string $blocks |
||||
47 | * |
||||
48 | * @return void |
||||
49 | * |
||||
50 | * @throws Exception |
||||
51 | */ |
||||
52 | public function render(array $fields, array $attributes, string $blocks): void |
||||
53 | { |
||||
54 | $globalVariables = compact('fields', 'attributes', 'blocks'); |
||||
55 | $localVariables = $this->with($fields); |
||||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||||
56 | |||||
57 | $data = array_merge($globalVariables, $localVariables); |
||||
58 | |||||
59 | echo static::capture($this->template(), $data); |
||||
60 | } |
||||
61 | |||||
62 | /** |
||||
63 | * Get the block's template. |
||||
64 | * |
||||
65 | * @return string |
||||
66 | */ |
||||
67 | protected function template(): string |
||||
68 | { |
||||
69 | if (empty($this->template)) { |
||||
70 | throw BlockException::forEmptyTemplate(); |
||||
71 | } |
||||
72 | |||||
73 | $template = locate_template($this->template); |
||||
0 ignored issues
–
show
The function
locate_template was not found. Maybe you did not declare it correctly or list all dependencies?
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() |
|||||
74 | if ($template === '') { |
||||
75 | throw BlockException::forNotFoundTemplate($this->template); |
||||
76 | } |
||||
77 | |||||
78 | return $template; |
||||
79 | } |
||||
80 | } |
||||
81 |