static-php-cli/src/SPC/command/DoctorCommand.php

86 lines
3.2 KiB
PHP
Raw Normal View History

2023-04-22 17:45:43 +08:00
<?php
declare(strict_types=1);
namespace SPC\command;
2023-04-22 21:23:12 +08:00
use SPC\doctor\CheckListHandler;
2023-09-09 10:04:20 +02:00
use SPC\doctor\CheckResult;
use SPC\exception\RuntimeException;
2023-04-22 17:45:43 +08:00
use Symfony\Component\Console\Attribute\AsCommand;
2023-10-31 01:48:49 +08:00
use function Laravel\Prompts\confirm;
2023-04-22 17:45:43 +08:00
#[AsCommand('doctor', 'Diagnose whether the current environment can compile normally')]
class DoctorCommand extends BaseCommand
{
public function configure(): void
2023-07-17 21:10:49 +08:00
{
$this->addOption('auto-fix', null, null, 'Automatically fix failed items (if possible)');
}
2023-04-22 17:45:43 +08:00
public function handle(): int
{
2023-04-22 21:23:12 +08:00
try {
2023-09-09 10:04:20 +02:00
$checker = new CheckListHandler();
$fix_policy = $this->input->getOption('auto-fix') ? FIX_POLICY_AUTOFIX : FIX_POLICY_PROMPT;
foreach ($checker->runChecks() as $check) {
if ($check->limit_os !== null && $check->limit_os !== PHP_OS_FAMILY) {
continue;
}
$this->output->write('Checking <comment>' . $check->item_name . '</comment> ... ');
$result = call_user_func($check->callback);
if ($result === null) {
$this->output->writeln('skipped');
} elseif ($result instanceof CheckResult) {
if ($result->isOK()) {
$this->output->writeln($result->getMessage() ?? 'ok');
continue;
}
// Failed
$this->output->writeln('<error>' . $result->getMessage() . '</error>');
switch ($fix_policy) {
case FIX_POLICY_DIE:
throw new RuntimeException('Some check items can not be fixed !');
case FIX_POLICY_PROMPT:
if ($result->getFixItem() !== '') {
2023-10-31 01:48:49 +08:00
$question = confirm('Do you want to fix it?');
if ($question) {
2023-09-09 10:04:20 +02:00
$checker->emitFix($this->output, $result);
} else {
throw new RuntimeException('You cancelled fix');
}
} else {
throw new RuntimeException('Some check items can not be fixed !');
}
break;
case FIX_POLICY_AUTOFIX:
if ($result->getFixItem() !== '') {
$this->output->writeln('Automatically fixing ' . $result->getFixItem() . ' ...');
$checker->emitFix($this->output, $result);
} else {
throw new RuntimeException('Some check items can not be fixed !');
}
break;
}
}
}
2023-04-22 21:23:12 +08:00
$this->output->writeln('<info>Doctor check complete !</info>');
} catch (\Throwable $e) {
$this->output->writeln('<error>' . $e->getMessage() . '</error>');
2023-09-09 10:04:20 +02:00
2023-04-30 12:42:19 +08:00
pcntl_signal(SIGINT, SIG_IGN);
2023-09-09 10:04:20 +02:00
2023-08-06 10:43:20 +08:00
return static::FAILURE;
2023-04-22 21:23:12 +08:00
}
2023-09-09 10:04:20 +02:00
2023-08-06 10:43:20 +08:00
return static::SUCCESS;
2023-04-22 17:45:43 +08:00
}
}