GenerateFarmHouseConfigJson.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace App\Module\Farm\Commands;
  3. use App\Module\Farm\Models\FarmHouseConfig;
  4. use Illuminate\Console\Command;
  5. use Illuminate\Support\Facades\DB;
  6. /**
  7. * 生成房屋配置表JSON数据命令
  8. *
  9. * 该命令用于从数据库中的房屋配置表生成JSON数据文件,供客户端使用。
  10. * 生成的JSON文件包含房屋等级的基本信息,如等级、产出加成、特殊土地上限等。
  11. * 该命令通常在房屋配置数据更新后运行,以确保客户端获取最新的配置数据。
  12. */
  13. class GenerateFarmHouseConfigJson extends Command
  14. {
  15. /**
  16. * 命令名称
  17. *
  18. * @var string
  19. */
  20. protected $signature = 'farm:generate-house-json';
  21. /**
  22. * 命令描述
  23. *
  24. * @var string
  25. */
  26. protected $description = '生成房屋配置JSON文件';
  27. /**
  28. * 生成房屋配置JSON数据
  29. *
  30. * @param bool $saveToFile 是否保存到文件
  31. * @return array|bool 生成的数据或失败标志
  32. */
  33. public static function generateJson()
  34. {
  35. try {
  36. // 获取所有房屋配置
  37. $configs = FarmHouseConfig::orderBy('level')->get();
  38. // 准备JSON数据
  39. $jsonData = [
  40. 'generated_ts' => time(),
  41. 'house_configs' => []
  42. ];
  43. foreach ($configs as $config) {
  44. $jsonData['house_configs'][] = [
  45. 'level' => $config->level,
  46. 'output_bonus' => $config->output_bonus,
  47. 'special_land_limit' => $config->special_land_limit,
  48. 'upgrade_materials' => $config->upgrade_materials,
  49. 'downgrade_days' => $config->downgrade_days,
  50. ];
  51. }
  52. return $jsonData;
  53. } catch (\Exception $e) {
  54. if (php_sapi_name() === 'cli') {
  55. echo "Error: Generate farm_house.json failed: {$e->getMessage()}\n";
  56. }
  57. return false;
  58. }
  59. }
  60. /**
  61. * 执行命令
  62. *
  63. * @return int
  64. */
  65. public function handle()
  66. {
  67. $this->info('开始生成房屋配置JSON文件...');
  68. try {
  69. // 直接调用静态方法生成JSON,而不通过缓存类
  70. $result = self::generateJson();
  71. if ($result !== false) {
  72. $this->info('房屋配置JSON文件生成成功');
  73. $this->info('共生成 ' . count($result['house_configs']) . ' 条配置数据');
  74. return Command::SUCCESS;
  75. } else {
  76. $this->error('生成房屋配置JSON文件失败');
  77. return Command::FAILURE;
  78. }
  79. } catch (\Exception $e) {
  80. $this->error('生成房屋配置JSON文件失败: ' . $e->getMessage());
  81. return Command::FAILURE;
  82. }
  83. }
  84. }