Repository navigation
Expand file tree
/
Copy pathApplication.php
More file actions
397 lines (328 loc) · 12.2 KB
/
Copy pathApplication.php
File metadata and controls
397 lines (328 loc) · 12.2 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
<?php
declare(strict_types=1);
/*
* This file is part of the PHPRegex package.
*
* (c) Younes ENNAJI <younes.ennaji.pro@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPRegex\Cli;
use PHPRegex\Cli\Command\CommandInterface;
use PHPRegex\Cli\Command\HelpCommand;
use PHPRegex\Cli\Command\JsonCommandInterface;
use PHPRegex\Parser\Internal\IniFlag;
use PHPRegex\Parser\Internal\JsonDocument;
/**
* @internal
*/
final class Application
{
/**
* The errors that stop PHP: no document follows them.
*/
private const FATAL_ERRORS = \E_ERROR | \E_PARSE | \E_CORE_ERROR | \E_COMPILE_ERROR | \E_USER_ERROR;
/**
* The bytes set aside during a JSON run for printing the envelope after
* PHP ran out of memory.
*/
private const MEMORY_RESERVE = 256 * 1024;
/**
* The output of the JSON run in progress, null between runs.
*/
private static ?Output $jsonRunOutput = null;
/**
* The process the JSON run in progress started in, null between runs.
*/
private static int|false|null $jsonRunPid = null;
/**
* Freed first when PHP stops a JSON run, null between runs.
*/
private static ?string $memoryReserve = null;
/**
* @var array<string, CommandInterface>
*/
private array $commands = [];
/**
* The commands as they were registered, without their aliases.
*
* @var array<int, CommandInterface>
*/
private array $registered = [];
public function __construct(
private readonly GlobalOptionsParser $globalOptionsParser,
private readonly Output $output,
private readonly CommandInterface $helpCommand,
) {}
public function register(CommandInterface $command): void
{
$this->registered[] = $command;
$this->commands[$command->getName()] = $command;
foreach ($command->getAliases() as $alias) {
$this->commands[$alias] = $command;
}
}
/**
* @param array<int, string> $argv
*/
public function run(array $argv): int
{
$parsed = $this->parseArguments($argv);
$options = $parsed->options;
$args = $parsed->args;
$this->configureOutput($options);
// The command's own options are not read yet: whether JSON was asked
// for is read from the whole command line.
if (!$this->asksForJson(\array_slice($argv, 1), $args)) {
return $this->dispatch($args, $options, false);
}
// Where ini_get() or ini_set() is disabled the setting is left as it
// is: the run goes on.
$displayErrors = \function_exists('ini_get') && \function_exists('ini_set') ? \ini_get('display_errors') : false;
if (false !== $displayErrors && IniFlag::displaysErrors($displayErrors)) {
// PHP's own diagnostics stay off stdout, which holds the document.
\ini_set('display_errors', 'stderr');
}
self::prepareFatalErrorReport($this->output);
try {
return $this->dispatch($args, $options, true);
} catch (\Throwable $e) {
// The boundary of the application: a failure no command caught
// still leaves stdout holding one document.
if ($this->output->hasWrittenDocument()) {
throw $e;
}
$this->output->writeDocument(JsonDocument::error($e->getMessage(), JsonDocument::STAGE_INTERNAL));
return CommandInterface::FAILURE;
} finally {
self::$jsonRunOutput = null;
self::$jsonRunPid = null;
self::$memoryReserve = null;
if (false !== $displayErrors) {
\ini_set('display_errors', $displayErrors);
}
}
}
/**
* @return array<int, CommandInterface>
*/
public function registeredCommands(): array
{
return $this->registered;
}
/**
* A JSON run PHP stopped with a fatal error never printed its document:
* the envelope takes its place, stage "internal", exit code 1. Nothing
* is printed for a run that already printed its document, nor once the
* run is over.
*
* The binary calls it at the shutdown of the process and exits with the
* code it returns: library code never exits.
*
* @internal
*
* @return int|null the exit code when the envelope was printed, null otherwise
*/
public static function reportFatalError(): ?int
{
// Reached at the shutdown of the process only: the tests run it in a
// child PHP process, which a fatal error stops. A forked worker runs
// the shutdown code of its parent too: what stops it is the parent's
// to report, from what the worker left.
if (null === self::$jsonRunPid || getmypid() !== self::$jsonRunPid) {
return null;
}
// Memory exhausted leaves none to print with: the reserve makes room.
self::$memoryReserve = null;
$output = self::$jsonRunOutput;
$error = error_get_last();
if (null === $output || $output->hasWrittenDocument() || null === $error || 0 === ($error['type'] & self::FATAL_ERRORS)) {
return null;
}
$output->writeDocument(JsonDocument::error('Fatal error: '.$error['message'], JsonDocument::STAGE_INTERNAL));
return CommandInterface::FAILURE;
}
/**
* Whether the command line asks for JSON of a command that has a JSON
* mode, or of a command it does not name: a command without one reports
* in text whatever the command line holds.
*
* @param array<int, string> $argv the command line after the binary
* @param array<int, string> $args the same without the global options
*/
private function asksForJson(array $argv, array $args): bool
{
if (!JsonRequest::in($argv)) {
return false;
}
$name = $args[0] ?? null;
if (null === $name) {
return true;
}
if ($this->isRegexArgument($name)) {
return false;
}
$command = $this->getCommand($name);
return null === $command || $command instanceof JsonCommandInterface;
}
/**
* Records the JSON run reportFatalError() reports on, and sets aside
* what printing the envelope takes: a run that exhausts the memory has
* none left for it.
*/
private static function prepareFatalErrorReport(Output $output): void
{
// PHP loads a class, and allocates the engine cache of a function,
// the first time it is used: each costs memory a run that exhausted
// it no longer has, so the envelope's path is used once now. No run
// is recorded yet: the report returns at once. What is left to
// allocate fits in the reserve, freed before it is needed.
self::reportFatalError();
JsonDocument::error('', JsonDocument::STAGE_INTERNAL);
self::$jsonRunOutput = $output;
self::$jsonRunPid = getmypid();
self::$memoryReserve = str_repeat('x', self::MEMORY_RESERVE);
}
/**
* @param array<int, string> $args
* @param bool $json whether errors are reported as the JSON envelope
*/
private function dispatch(array $args, GlobalOptions $options, bool $json): int
{
if (null !== $options->error) {
return $this->handleError($options->error, $json);
}
if ($options->help) {
return $this->showHelpFor($args, $options);
}
$commandName = $this->resolveCommandName($args);
if (null === $commandName) {
return $this->showHelpAndExit($options);
}
if ($this->isRegexArgument($commandName)) {
return $this->runAsHighlight($args, $options);
}
$command = $this->getCommand($commandName);
if (null === $command) {
if ($json) {
// An option before the command name: --json analyze /a/.
$hint = str_starts_with($commandName, '-') ? ' Options go after the command name.' : '';
return $this->handleError("Unknown command: {$commandName}.".$hint, true);
}
return $this->handleUnknownCommand($commandName, $options);
}
$commandArgs = $this->extractCommandArgs($args);
$input = $this->createInput($commandName, $commandArgs, $options);
return $command->run($input, $this->output);
}
/**
* @param array<int, string> $argv
*/
private function parseArguments(array $argv): ParsedGlobalOptions
{
$args = $argv;
array_shift($args);
return $this->globalOptionsParser->parse($args);
}
private function configureOutput(GlobalOptions $options): void
{
$this->output->setAnsi($this->shouldUseAnsi($options->ansi));
$this->output->setQuiet($options->quiet);
}
private function shouldUseAnsi(?bool $forced): bool
{
return $forced ?? (\function_exists('posix_isatty') && posix_isatty(\STDOUT));
}
private function handleError(string $errorMessage, bool $json = false): int
{
if ($json) {
$this->output->writeDocument(JsonDocument::error($errorMessage, JsonDocument::STAGE_USAGE));
return CommandInterface::INVALID;
}
$this->output->write($this->output->error('Error: '.$errorMessage."\n"));
return CommandInterface::INVALID;
}
/**
* @param array<int, string> $args
*/
private function showHelpFor(array $args, GlobalOptions $options): int
{
$targetCommand = $args[0] ?? null;
return $this->help()->run(
new Input('help', null !== $targetCommand ? [$targetCommand] : [], $options, []),
$this->output,
);
}
/**
* @param array<int, string> $args
*/
private function resolveCommandName(array $args): ?string
{
return $args[0] ?? null;
}
private function showHelpAndExit(GlobalOptions $options): int
{
$this->help()->run(new Input('help', [], $options, []), $this->output);
return CommandInterface::INVALID;
}
/**
* @param array<int, string> $args
*/
private function runAsHighlight(array $args, GlobalOptions $options): int
{
$command = $this->getCommand('highlight');
if (null === $command) {
return $this->handleError('Highlight command is not registered.');
}
$input = new Input('highlight', $args, $options, []);
return $command->run($input, $this->output);
}
private function isRegexArgument(string $value): bool
{
return str_starts_with($value, '/');
}
private function getCommand(string $name): ?CommandInterface
{
return $this->commands[$name] ?? null;
}
/**
* Hand the help command what the application actually knows, so that the
* list it prints cannot drift from the list it can run.
*/
private function help(): CommandInterface
{
return $this->helpCommand instanceof HelpCommand
? $this->helpCommand->withCommands($this->registered)
: $this->helpCommand;
}
/**
* @param array<int, string> $args
*
* @return array<int, string>
*/
private function extractCommandArgs(array $args): array
{
return \array_slice($args, 1);
}
private function handleUnknownCommand(string $commandName, GlobalOptions $options): int
{
$this->output->write($this->output->error("Unknown command: {$commandName}\n\n"));
$this->help()->run(new Input('help', [], $options, []), $this->output);
return CommandInterface::INVALID;
}
/**
* @param array<int, string> $commandArgs
*/
private function createInput(
string $commandName,
array $commandArgs,
GlobalOptions $options,
): Input {
$regexOptions = array_filter(
['php_version' => $options->phpVersion, 'pcre_version' => $options->pcreVersion],
static fn (?string $version): bool => null !== $version,
);
return new Input($commandName, $commandArgs, $options, $regexOptions);
}
}