ExportGlossary.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Services\TermService;
  4. use Illuminate\Console\Command;
  5. use Illuminate\Support\Facades\File;
  6. use Illuminate\Support\Facades\Log;
  7. class ExportGlossary extends Command
  8. {
  9. /**
  10. * The name and signature of the console command.
  11. * php artisan export:export-glossary zh-Hans
  12. *
  13. * @var string
  14. */
  15. protected $signature = 'export:export-glossary {lang}';
  16. /**
  17. * The console command description.
  18. *
  19. * @var string
  20. */
  21. protected $description = '导出术语表';
  22. protected TermService $termService;
  23. public function __construct(TermService $termService)
  24. {
  25. $this->termService = $termService;
  26. parent::__construct();
  27. }
  28. /**
  29. * Execute the console command.
  30. */
  31. public function handle()
  32. {
  33. Log::info('task export offline sentence-table start');
  34. $lang = $this->argument('lang');
  35. // 创建文件夹
  36. $base = 'app/tmp/export/offline';
  37. $exportDir = storage_path($base);
  38. if (! is_dir($exportDir)) {
  39. $res = mkdir($exportDir, 0755, true);
  40. if (! $res) {
  41. $this->error('mkdir fail path='.$exportDir);
  42. return 1;
  43. } else {
  44. $this->info('make dir successful '.$exportDir);
  45. }
  46. }
  47. // 创建临时文件夹\
  48. $dirname = $exportDir.'/'.'wikipali_glossary_'.date('YmdHis');
  49. $tmp = mkdir($dirname, 0755, true);
  50. if (! $tmp) {
  51. $this->error('mkdir fail path='.$dirname);
  52. return 1;
  53. } else {
  54. $this->info('make dir successful '.$dirname);
  55. }
  56. $fpIndex = fopen($dirname.'/index.md', 'w');
  57. if ($fpIndex === false) {
  58. exit('无法创建索引文件');
  59. }
  60. // 创建json文件
  61. $this->info('export start'.$lang);
  62. $filename = 'glossary_'.$lang.'.jsonl';
  63. $exportFile = $dirname.'/'.$filename;
  64. $fp = fopen($exportFile, 'w');
  65. if ($fp === false) {
  66. exit('无法创建文件');
  67. }
  68. $start = time();
  69. // **业务逻辑 */
  70. $data = $this->termService->getCommunityGlossary($lang);
  71. foreach ($data['items'] as $key => $value) {
  72. fwrite($fp, json_encode($value, JSON_UNESCAPED_UNICODE)."\n");
  73. }
  74. fclose($fpIndex);
  75. $this->info((time() - $start).' seconds');
  76. $this->call('export:zip2', [
  77. 'id' => 'wikipali_glossary',
  78. 'filename' => $dirname,
  79. 'title' => 'wikipali glossary of community',
  80. 'format' => 'jsonl',
  81. ]);
  82. sleep(5);
  83. File::deleteDirectory($dirname);
  84. return 0;
  85. }
  86. }