static-php-cli/src/SPC/command/dev/SortConfigCommand.php

68 lines
2.8 KiB
PHP
Raw Normal View History

2023-03-18 17:32:21 +08:00
<?php
declare(strict_types=1);
namespace SPC\command\dev;
2023-03-18 17:32:21 +08:00
use SPC\command\BaseCommand;
2023-03-18 17:32:21 +08:00
use SPC\exception\FileSystemException;
use SPC\exception\ValidationException;
use SPC\store\FileSystem;
use SPC\util\ConfigValidator;
2023-04-22 17:45:43 +08:00
use Symfony\Component\Console\Attribute\AsCommand;
2023-03-18 17:32:21 +08:00
use Symfony\Component\Console\Input\InputArgument;
/**
* Modify config file: sort lib, ext, source by name.
2023-03-18 17:32:21 +08:00
*/
#[AsCommand('dev:sort-config', 'After config edited, sort it by alphabet', ['sort-config'])]
2023-03-18 17:32:21 +08:00
class SortConfigCommand extends BaseCommand
{
public function configure(): void
2023-03-18 17:32:21 +08:00
{
$this->addArgument('config-name', InputArgument::REQUIRED, 'Your config to be sorted, you can sort "lib", "source" and "ext".');
}
/**
* @throws ValidationException
* @throws FileSystemException
*/
2023-04-22 17:45:43 +08:00
public function handle(): int
2023-03-18 17:32:21 +08:00
{
2023-04-22 17:45:43 +08:00
switch ($name = $this->getArgument('config-name')) {
2023-03-18 17:32:21 +08:00
case 'lib':
$file = json_decode(FileSystem::readFile(ROOT_DIR . '/config/lib.json'), true);
ConfigValidator::validateLibs($file);
ksort($file);
if (!file_put_contents(ROOT_DIR . '/config/lib.json', json_encode($file, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE))) {
$this->output->writeln('<error>Write file lib.json failed!</error>');
return static::FAILURE;
}
2023-03-18 17:32:21 +08:00
break;
case 'source':
$file = json_decode(FileSystem::readFile(ROOT_DIR . '/config/source.json'), true);
ConfigValidator::validateSource($file);
2023-04-30 12:42:19 +08:00
uksort($file, fn ($a, $b) => $a === 'php-src' ? -1 : ($b === 'php-src' ? 1 : ($a < $b ? -1 : 1)));
if (!file_put_contents(ROOT_DIR . '/config/source.json', json_encode($file, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE))) {
$this->output->writeln('<error>Write file source.json failed!</error>');
return static::FAILURE;
}
2023-03-18 17:32:21 +08:00
break;
case 'ext':
$file = json_decode(FileSystem::readFile(ROOT_DIR . '/config/ext.json'), true);
ConfigValidator::validateExts($file);
ksort($file);
if (!file_put_contents(ROOT_DIR . '/config/ext.json', json_encode($file, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE))) {
$this->output->writeln('<error>Write file ext.json failed!</error>');
return static::FAILURE;
}
2023-03-18 17:32:21 +08:00
break;
default:
2023-04-22 17:45:43 +08:00
$this->output->writeln("<error>invalid config name: {$name}</error>");
2023-03-18 17:32:21 +08:00
return 1;
}
2023-04-22 17:45:43 +08:00
$this->output->writeln('<info>sort success</info>');
2023-08-06 10:43:20 +08:00
return static::SUCCESS;
2023-03-18 17:32:21 +08:00
}
}