ExportGlossary.php 2.7 KB

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