CoreExtensionConfigCommand.php 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. declare(strict_types=1);
  3. namespace SixShop\System\Command;
  4. use SixShop\System\ExtensionManager;
  5. use SixShop\System\Migrate;
  6. use SixShop\System\Model\ExtensionModel;
  7. use think\console\Command;
  8. use think\db\exception\PDOException;
  9. use function SixShop\Core\extension_name_list;
  10. class CoreExtensionConfigCommand extends Command
  11. {
  12. public function configure(): void
  13. {
  14. $this->setName('core:config')
  15. ->setDescription('Set the core extension default configuration')
  16. ->addOption('force', 'f', null, 'Force update the core extension default configuration');
  17. }
  18. public function handle(): void
  19. {
  20. $start = microtime(true);
  21. $force = $this->input->getOption('force');
  22. $extensionManager = $this->app->make(ExtensionManager::class);
  23. // 确保系统扩展迁移已安装
  24. $moduleList = array_diff(extension_name_list(), ['system']);
  25. array_unshift($moduleList, 'system');
  26. try {
  27. $installModuleList = ExtensionModel::where('status', '>', 1)
  28. ->column('id');
  29. } catch (PDOException $e) {
  30. $installModuleList = ['system'];
  31. }
  32. foreach ($moduleList as $moduleName) {
  33. $extension = $extensionManager->getExtension($moduleName);
  34. try {
  35. $config = $extensionManager->getExtensionConfig($moduleName);
  36. } catch (PDOException $e) {
  37. $config = [];
  38. }
  39. if (in_array($moduleName, $installModuleList)) {
  40. $migrate = app(Migrate::class, [$this->app, $moduleName], true);
  41. if ($force) {
  42. $migrate->uninstall();
  43. $this->output->writeln("Uninstall extension migration for module: $moduleName");
  44. }
  45. $installVersions = $migrate->install();
  46. foreach ($installVersions as $version) {
  47. $this->output->writeln("Install extension migration for module: $moduleName, version: $version");
  48. }
  49. if (empty($config) || $force) {
  50. $updateData = [];
  51. $formConfig = $extension->getConfig();
  52. foreach ($formConfig as $item) {
  53. if (isset($item['value'])) {
  54. $updateData[$item['field']] = $item['value'];
  55. $value = is_array($item['value']) ? json_encode($item['value'], JSON_UNESCAPED_UNICODE) : $item['value'];
  56. $this->output->writeln("Set extension default configuration for module: $moduleName, field: {$item['field']}, value: $value");
  57. }
  58. }
  59. if (!empty($updateData)) {
  60. $extensionManager->saveConfig($moduleName, $updateData);
  61. }
  62. }
  63. }
  64. }
  65. $end = microtime(true);
  66. $this->output->writeln('');
  67. $this->output->writeln('<comment>All Done. Took ' . sprintf('%.4fs', $end - $start) . '</comment>');
  68. }
  69. }