GenerateItemsJsonCommand.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. namespace App\Module\GameItems\Commands;
  3. use App\Module\Game\DCache\ItemJsonConfig;
  4. use App\Module\Game\Services\JsonConfigService;
  5. use App\Module\GameItems\Config\NumericAttributesWhitelist;
  6. use Carbon\Carbon;
  7. use Illuminate\Console\Command;
  8. use App\Module\GameItems\Models\Item;
  9. use Illuminate\Support\Facades\Log;
  10. /**
  11. * 生成物品配置表JSON数据命令
  12. *
  13. * 该命令用于从数据库中的物品表生成物品JSON数据文件,供客户端使用。
  14. * 生成的JSON文件包含物品的基本信息,如ID、名称、描述、售价和显示属性等。
  15. * 该命令通常在物品数据更新后运行,以确保客户端获取最新的物品数据。
  16. */
  17. class GenerateItemsJsonCommand extends Command
  18. {
  19. /**
  20. * 命令名称和签名
  21. *
  22. * @var string
  23. */
  24. protected $signature = 'gameitems:generate-json';
  25. /**
  26. * 命令描述
  27. *
  28. * @var string
  29. */
  30. protected $description = 'Generate items.json from Item table';
  31. /**
  32. * 执行命令
  33. */
  34. /**
  35. * 生成物品JSON数据
  36. *
  37. * @param bool $saveToFile 是否保存到文件
  38. * @return array|bool 生成的数据或失败标志
  39. */
  40. public static function generateJson()
  41. {
  42. try {
  43. // 查询Item表中的数据
  44. $items = Item::query()
  45. ->select([
  46. 'id',
  47. 'name',
  48. 'description',
  49. 'sell_price',
  50. 'display_attributes',
  51. 'numeric_attributes'
  52. ])
  53. ->get()
  54. ->map(function ($item) {
  55. // 过滤numeric_attributes,只保留白名单中的属性
  56. $numericAttributes = null;
  57. if ($item->numeric_attributes) {
  58. $numericAttributes = NumericAttributesWhitelist::filter($item->numeric_attributes);
  59. }
  60. return [
  61. 'id' => $item->id,
  62. 'name' => $item->name,
  63. 'description' => $item->description,
  64. 'sell_price' => $item->sell_price,
  65. 'display_attributes' => $item->display_attributes,
  66. 'numeric_attributes' => $numericAttributes
  67. ];
  68. })
  69. ->toArray();
  70. // 准备完整数据,包含生成时间
  71. $data = [
  72. 'generated_ts' => time(),
  73. 'items' => $items
  74. ];
  75. return $data;
  76. } catch (\Exception $e) {
  77. Log::error('Generate items.json failed: ' . $e->getMessage());
  78. return false;
  79. }
  80. }
  81. public function handle()
  82. {
  83. if (ItemJsonConfig::getData([], true)) {
  84. $this->info('Successfully generated items.json with timestamp');
  85. } else {
  86. $this->error('Failed to generate items.json');
  87. }
  88. }
  89. }