GenerateItemsJsonCommand.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace App\Module\GameItems\Commands;
  3. use App\Module\Game\DCache\ItemJsonConfig;
  4. use App\Module\Game\Services\JsonConfigService;
  5. use Illuminate\Console\Command;
  6. use App\Module\GameItems\Models\Item;
  7. use Illuminate\Support\Facades\File;
  8. use Illuminate\Support\Facades\Log;
  9. class GenerateItemsJsonCommand extends Command
  10. {
  11. /**
  12. * 命令名称和签名
  13. *
  14. * @var string
  15. */
  16. protected $signature = 'gameitems:generate-json';
  17. /**
  18. * 命令描述
  19. *
  20. * @var string
  21. */
  22. protected $description = 'Generate items.json from Item table';
  23. /**
  24. * 执行命令
  25. */
  26. /**
  27. * 生成物品JSON数据
  28. */
  29. public static function generateJson(): bool
  30. {
  31. try {
  32. // 查询Item表中的数据
  33. $items = Item::query()
  34. ->select([
  35. 'id',
  36. 'name',
  37. 'description',
  38. 'sell_price',
  39. 'display_attributes'
  40. ])
  41. ->get()
  42. ->map(function ($item) {
  43. return [
  44. 'id' => $item->id,
  45. 'name' => $item->name,
  46. 'description' => $item->description,
  47. 'sell_price' => $item->sell_price,
  48. 'display_attributes' => $item->display_attributes
  49. ];
  50. })
  51. ->toArray();
  52. // 确保public/json目录存在
  53. $directory = public_path('json');
  54. if (!File::exists($directory)) {
  55. if (!File::makeDirectory($directory, 0755, true)) {
  56. Log::error('Failed to create directory: ' . $directory);
  57. return false;
  58. }
  59. }
  60. // 检查目录是否可写
  61. if (!is_writable($directory)) {
  62. Log::error('Directory is not writable: ' . $directory);
  63. return false;
  64. }
  65. // 准备完整数据,包含生成时间
  66. $data = [
  67. 'generated_at' => now()->toDateTimeString(),
  68. 'items' => $items
  69. ];
  70. return $data;
  71. } catch (\Exception $e) {
  72. Log::error('Generate items.json failed: ' . $e->getMessage());
  73. return false;
  74. }
  75. }
  76. public function handle()
  77. {
  78. if (ItemJsonConfig::getData([], true)) {
  79. $this->info('Successfully generated items.json with timestamp');
  80. } else {
  81. $this->error('Failed to generate items.json');
  82. }
  83. }
  84. }