SyncItemsJsonTool.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace App\Module\GameItems\AdminControllers\Tools;
  3. use Dcat\Admin\Grid\Tools\AbstractTool;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\Log;
  6. class SyncItemsJsonTool extends AbstractTool
  7. {
  8. protected $shouldDisplay;
  9. protected $style = 'btn btn-danger waves-effect';
  10. public function __construct(bool $shouldDisplay = true)
  11. {
  12. $this->shouldDisplay = $shouldDisplay;
  13. }
  14. public function title()
  15. {
  16. return '立即同步';
  17. }
  18. public function confirm()
  19. {
  20. return '确定要立即同步JSON数据吗?';
  21. }
  22. public function handle(Request $request)
  23. {
  24. try {
  25. $success = \App\Module\GameItems\Commands\GenerateItemsJsonCommand::generateJson();
  26. if (!$success) {
  27. Log::error('Sync items.json failed - see previous logs for details');
  28. return $this->response()->error('同步失败:请检查日志获取详细信息');
  29. }
  30. return $this->response()->success('同步成功')->refresh();
  31. } catch (\Exception $e) {
  32. Log::error('Sync items.json exception: '.$e->getMessage());
  33. return $this->response()->error('同步失败:'.$e->getMessage());
  34. }
  35. }
  36. public function render()
  37. {
  38. if (!$this->shouldDisplay) {
  39. return '';
  40. }
  41. return parent::render();
  42. }
  43. public static function shouldDisplay(): bool
  44. {
  45. $jsonPath = public_path('json/items.json');
  46. if (!file_exists($jsonPath)) {
  47. return true;
  48. }
  49. $json = json_decode(file_get_contents($jsonPath), true);
  50. $generatedAt = \Carbon\Carbon::parse($json['generated_at']);
  51. $lastUpdated = \Carbon\Carbon::parse(\App\Module\GameItems\Models\Item::max('updated_at'));
  52. return $generatedAt->lt($lastUpdated);
  53. }
  54. }