TranArticle.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace App\Jobs;
  3. use App\Http\Models\Article;
  4. use Illuminate\Bus\Queueable;
  5. use Illuminate\Queue\SerializesModels;
  6. use Illuminate\Queue\InteractsWithQueue;
  7. use Illuminate\Contracts\Queue\ShouldQueue;
  8. use Illuminate\Foundation\Bus\Dispatchable;
  9. use Illuminate\Support\Facades\DB;
  10. use GuzzleHttp\Client;
  11. class TranArticle implements ShouldQueue
  12. {
  13. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  14. public $timeout = 560;
  15. protected $id;
  16. protected $content;
  17. public $tries = 1;
  18. public function __construct($id, $content)
  19. {
  20. $this->id = $id;
  21. $this->content = $content;
  22. }
  23. /**
  24. * Execute the job.
  25. *
  26. * @return void
  27. */
  28. public function handle()
  29. {
  30. $article = Article::query()->where(['id' => $this->id])->first();
  31. if (!$article) {
  32. return;
  33. }
  34. if (strlen(trim($this->content)) > 2) {
  35. $client = new Client;
  36. $response = $client->post('http://translate.api.yinqingli.net/translate/translate', [
  37. 'form_params' => [
  38. 'q' => $this->content,
  39. 'source' => 'zh-CN',
  40. 'target' => 'en'
  41. ],
  42. 'timeout' => 500
  43. ]);
  44. $result = json_decode($response->getBody()->getContents(), true);
  45. $data['translate_content'] = $result['data']['translations'][0]['translatedText'] ?? '';
  46. $data['translate_words'] = word_count($data['translate_content']) + word_count($article->translate_title);
  47. $data['init_tran_content'] = $data['translate_content'];
  48. $article->update($data);
  49. // Article::query()->where(['id' => $this->id])->update($data);
  50. // DB::table('test')->insert([
  51. // 'user_id' => $this->id,
  52. // 'content' => 'success'
  53. // ]);
  54. }
  55. }
  56. }