InstallWordBook.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\BookWord;
  4. use App\Tools\Tools;
  5. use Illuminate\Console\Command;
  6. use Illuminate\Support\Facades\DB;
  7. use Illuminate\Support\Facades\Log;
  8. class InstallWordBook extends Command
  9. {
  10. /**
  11. * The name and signature of the console command.
  12. *
  13. * @var string
  14. */
  15. protected $signature = 'install:wordbook {from?} {to?}';
  16. /**
  17. * The console command description.
  18. *
  19. * @var string
  20. */
  21. protected $description = 'install palibook word list in each book';
  22. /**
  23. * Create a new command instance.
  24. *
  25. * @return void
  26. */
  27. public function __construct()
  28. {
  29. parent::__construct();
  30. }
  31. /**
  32. * Execute the console command.
  33. *
  34. * @return int
  35. */
  36. public function handle()
  37. {
  38. if (Tools::isStop()) {
  39. return 0;
  40. }
  41. $startTime = time();
  42. $this->info('instert word in palibook ');
  43. Log::info('instert word in palibook ');
  44. $_from = $this->argument('from');
  45. $_to = $this->argument('to');
  46. if (empty($_from) && empty($_to)) {
  47. $_from = 1;
  48. $_to = 217;
  49. } elseif (empty($_to)) {
  50. $_to = $_from;
  51. }
  52. $bar = $this->output->createProgressBar($_to - $_from + 1);
  53. for ($book = $_from; $book <= $_to; $book++) {
  54. Log::info('doing '.($book));
  55. // 删除目标数据库中数据
  56. BookWord::where('book', $book)->delete();
  57. // 分类汇总得到单词表
  58. $bookword = [];
  59. $fileId = $book - 1;
  60. if (($fpoutput = fopen(config('mint.path.paliword_book')."/{$fileId}_words.csv", 'r')) !== false) {
  61. $count = 0;
  62. while (($data = fgetcsv($fpoutput, 0, ',')) !== false) {
  63. $book = $data[1];
  64. if (isset($bookword[$data[3]])) {
  65. $bookword[$data[3]]++;
  66. } else {
  67. $bookword[$data[3]] = 1;
  68. }
  69. $count++;
  70. }
  71. } else {
  72. Log::error('open csv fail');
  73. continue;
  74. }
  75. DB::transaction(function () use ($book, $bookword) {
  76. foreach ($bookword as $key => $value) {
  77. $newData = [
  78. 'book' => $book,
  79. 'wordindex' => $key,
  80. 'count' => $value,
  81. ];
  82. BookWord::create($newData);
  83. }
  84. });
  85. $bar->advance();
  86. }
  87. $bar->finish();
  88. $msg = 'all done in '.time() - $startTime.'s';
  89. $this->info($msg.PHP_EOL);
  90. Log::info($msg);
  91. return 0;
  92. }
  93. }