| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128 |
- <?php
- namespace App\Module\GameItems\Commands;
- use App\Module\Game\DCache\ItemJsonConfig;
- use App\Module\Game\Services\JsonConfigService;
- use Carbon\Carbon;
- use Illuminate\Console\Command;
- use App\Module\GameItems\Models\Item;
- use Illuminate\Support\Facades\File;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Facades\Storage;
- /**
- * 生成物品配置表JSON数据命令
- *
- * 该命令用于从数据库中的物品表生成物品JSON数据文件,供客户端使用。
- * 生成的JSON文件包含物品的基本信息,如ID、名称、描述、售价和显示属性等。
- * 该命令通常在物品数据更新后运行,以确保客户端获取最新的物品数据。
- */
- class GenerateItemsJsonCommand extends Command
- {
- /**
- * 命令名称和签名
- *
- * @var string
- */
- protected $signature = 'gameitems:generate-json';
- /**
- * 命令描述
- *
- * @var string
- */
- protected $description = 'Generate items.json from Item table';
- /**
- * 执行命令
- */
- /**
- * 生成物品JSON数据
- *
- * @param bool $saveToFile 是否保存到文件
- * @return array|bool 生成的数据或失败标志
- */
- public static function generateJson()
- {
- try {
- // 查询Item表中的数据
- $items = Item::query()
- ->select([
- 'id',
- 'name',
- 'description',
- 'sell_price',
- 'display_attributes',
- 'numeric_attributes'
- ])
- ->get()
- ->map(function ($item) {
- return [
- 'id' => $item->id,
- 'name' => $item->name,
- 'description' => $item->description,
- 'sell_price' => $item->sell_price,
- 'display_attributes' => $item->display_attributes,
- 'numeric_attributes' => $item->numeric_attributes
- ];
- })
- ->toArray();
- // 准备完整数据,包含生成时间
- $data = [
- 'generated_ts' => time(),
- 'items' => $items
- ];
- return $data;
- } catch (\Exception $e) {
- Log::error('Generate items.json failed: ' . $e->getMessage());
- return false;
- }
- }
- /**
- * 将JSON数据保存到文件
- *
- * @param array $data 要保存的数据
- * @return bool 是否保存成功
- */
- protected static function saveJsonToFile(array $data): bool
- {
- try {
- // 确保目录存在
- $directory = 'public/json';
- if (!File::exists($directory)) {
- File::makeDirectory($directory, 0755, true);
- }
- // 将数据保存为JSON文件
- $jsonContent = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
- $filePath = $directory . '/items.json';
- File::put($filePath, $jsonContent);
- Log::info('Items JSON file saved to: ' . $filePath);
- return true;
- } catch (\Exception $e) {
- Log::error('Save items.json to file failed: ' . $e->getMessage());
- return false;
- }
- }
- public function handle()
- {
- if (ItemJsonConfig::getData([], true)) {
- $this->info('Successfully generated items.json with timestamp');
- $this->info('JSON file saved to public/json/items.json');
- } else {
- $this->error('Failed to generate items.json');
- }
- }
- }
|