|
15 | 15 |
|
16 | 16 | use function Tempest\Support\arr; |
17 | 17 | use function Tempest\Support\path; |
| 18 | +use function Tempest\Support\str; |
18 | 19 |
|
19 | 20 | final readonly class TempestViewCompiler |
20 | 21 | { |
@@ -49,7 +50,10 @@ public function compile(string|View $view): string |
49 | 50 | // 5. Compile to PHP |
50 | 51 | $compiled = $this->compileElements($elements); |
51 | 52 |
|
52 | | - return $compiled; |
| 53 | + // 6. Cleanup compiled PHP |
| 54 | + $cleaned = $this->cleanupCompiled($compiled); |
| 55 | + |
| 56 | + return $cleaned; |
53 | 57 | } |
54 | 58 |
|
55 | 59 | private function retrieveTemplate(string|View $view): string |
@@ -172,4 +176,38 @@ private function compileElements(array $elements): string |
172 | 176 | ->implode(PHP_EOL) |
173 | 177 | ->toString(); |
174 | 178 | } |
| 179 | + |
| 180 | + private function cleanupCompiled(string $compiled): string |
| 181 | + { |
| 182 | + // Remove strict type declarations |
| 183 | + $compiled = str($compiled)->replace('declare(strict_types=1);', ''); |
| 184 | + |
| 185 | + // Cleanup and bundle imports |
| 186 | + $imports = arr(); |
| 187 | + |
| 188 | + $compiled = $compiled->replaceRegex("/^\s*use (function )?.*;/m", function (array $matches) use (&$imports) { |
| 189 | + // The import contains escaped slashes, meaning it's a var_exported string; we can ignore those |
| 190 | + if (str_contains($matches[0], '\\\\')) { |
| 191 | + return $matches[0]; |
| 192 | + } |
| 193 | + |
| 194 | + $imports[$matches[0]] = $matches[0]; |
| 195 | + |
| 196 | + return ''; |
| 197 | + }); |
| 198 | + |
| 199 | + $compiled = $compiled->prepend( |
| 200 | + sprintf( |
| 201 | + '<?php |
| 202 | +%s |
| 203 | +?>', |
| 204 | + $imports->implode(PHP_EOL), |
| 205 | + ), |
| 206 | + ); |
| 207 | + |
| 208 | + // Remove empty PHP blocks |
| 209 | + $compiled = $compiled->replaceRegex('/<\?php\s*\?>/', ''); |
| 210 | + |
| 211 | + return $compiled->toString(); |
| 212 | + } |
175 | 213 | } |
0 commit comments