-
Notifications
You must be signed in to change notification settings - Fork 0
/
StreamCompiler.php
51 lines (42 loc) · 1.33 KB
/
StreamCompiler.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
<?php
declare(strict_types=1);
namespace Emonkak\Sharp\Compiler;
/**
* @extends AbstractCompiler<resource>
*/
class StreamCompiler extends AbstractCompiler
{
private string $filename;
private string $mode;
public function __construct(string $filename = 'php://memory', string $mode = 'r+')
{
$this->filename = $filename;
$this->mode = $mode;
}
protected function compileSource(string $body, CompilerContext $context): string
{
$filename = var_export($this->filename, true);
$mode = var_export($this->mode, true);
return <<<EOL
<?php return static function(\$__variables) {
\$__variables += ['__sections' => [], '__stacks' => [], '__contents' => fopen($filename, $mode)];
extract(\$__variables, EXTR_SKIP | EXTR_REFS);
$body
return \$__contents;
};
EOL;
}
protected function compileStatement(string $name, string $parameters, CompilerContext $context): string
{
$statement = parent::compileStatement($name, $parameters, $context);
return $statement . "\n";
}
protected function compileEcho(string $expression, CompilerContext $context): string
{
return "fwrite(\$__contents, $expression);\n";
}
protected function compileYield(string $expression, CompilerContext $context): string
{
return $expression . ";\n";
}
}