-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathindex.php
More file actions
101 lines (82 loc) · 2.88 KB
/
Copy pathindex.php
File metadata and controls
101 lines (82 loc) · 2.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
use Psy\Exception\BreakException;
use TweakPHP\Client\Cli;
use TweakPHP\Client\Loader;
require __DIR__.'/vendor/autoload.php';
$arguments = $argv;
if (count($arguments) < 3) {
echo 'Invalid arguments'.PHP_EOL;
exit(1);
}
$command = $arguments[2];
$supportedCommands = [
'info',
'execute',
'execute-stream',
];
if (! in_array($command, $supportedCommands, true)) {
echo 'Invalid command'.PHP_EOL;
exit(1);
}
$writeStreamEvent = static function (array $event): void {
fwrite(STDOUT, 'TWEAKPHP_STREAM:'.json_encode($event, JSON_INVALID_UTF8_SUBSTITUTE).PHP_EOL);
fflush(STDOUT);
};
$writeError = static function (Throwable $exception) use ($command, $writeStreamEvent): void {
$error = [
'class' => get_class($exception),
'message' => $exception->getMessage(),
];
if ($command === 'execute-stream') {
$writeStreamEvent([
'type' => 'error',
'error' => $error,
]);
return;
}
echo 'TWEAKPHP_ERROR:'.json_encode($error, JSON_INVALID_UTF8_SUBSTITUTE).PHP_EOL;
};
$customLoader = Cli::getArgument('loader');
try {
$loader = Loader::load($arguments[1], $customLoader ?: null);
if ($loader === null) {
throw new RuntimeException('No supported project found. Make sure the path contains a Composer project (vendor/autoload.php).');
}
$loader->init();
if (in_array($command, ['execute', 'execute-stream'], true)) {
if (count($arguments) < 4) {
throw new InvalidArgumentException('Missing Base64-encoded PHP code.');
}
$code = base64_decode($arguments[3], true);
if ($code === false) {
throw new InvalidArgumentException('Invalid Base64-encoded PHP code.');
}
}
switch ($command) {
case 'info':
echo json_encode([
'name' => $loader->name(),
'version' => $loader->version(),
'php_version' => phpversion(),
], JSON_INVALID_UTF8_SUBSTITUTE).PHP_EOL;
break;
case 'execute':
echo 'TWEAKPHP_RESULT:'.json_encode($loader->execute($code), JSON_INVALID_UTF8_SUBSTITUTE).PHP_EOL;
break;
case 'execute-stream':
$streamFailed = false;
$streamExitCode = 1;
$loader->executeStreaming($code, static function (array $event) use (&$streamFailed, &$streamExitCode, $writeStreamEvent): void {
$streamFailed = $streamFailed || ($event['type'] ?? null) === 'error';
$streamExitCode = $event['error']['exit_code'] ?? $streamExitCode;
$writeStreamEvent($event);
});
if ($streamFailed) {
exit($streamExitCode);
}
break;
}
} catch (Throwable $exception) {
$writeError($exception);
exit($exception instanceof BreakException ? $exception->getCode() : 1);
}