SlugTranslateHandler.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * app(SlugTranslateHandler::class)->translate($content);
  4. */
  5. namespace App\Handlers;
  6. use GuzzleHttp\Client;
  7. use Overtrue\Pinyin\Pinyin;
  8. class SlugTranslateHandler
  9. {
  10. public function translate($text)
  11. {
  12. // 实例化 HTTP 客户端
  13. $http = new Client;
  14. // 初始化配置信息
  15. $api = 'http://api.fanyi.baidu.com/api/trans/vip/translate?';
  16. $appid = config('services.baidu_translate.appid');
  17. $key = config('services.baidu_translate.key');
  18. $salt = time();
  19. // 如果没有配置百度翻译,自动使用兼容的拼音方案
  20. if (empty($appid) || empty($key)) {
  21. return $this->pinyin($text);
  22. }
  23. // 根据文档,生成 sign
  24. // http://api.fanyi.baidu.com/api/trans/product/apidoc
  25. // appid+q+salt+密钥 的MD5值
  26. $sign = md5($appid. $text . $salt . $key);
  27. // 构建请求参数
  28. $query = http_build_query([
  29. "q" => $text,
  30. "from" => "zh",
  31. "to" => "en",
  32. "appid" => $appid,
  33. "salt" => $salt,
  34. "sign" => $sign,
  35. ]);
  36. // 发送 HTTP Get 请求
  37. $response = $http->get($api.$query);
  38. $result = json_decode($response->getBody(), true);
  39. /**
  40. 获取结果,如果请求成功,dd($result) 结果如下:
  41. array:3 [▼
  42. "from" => "zh"
  43. "to" => "en"
  44. "trans_result" => array:1 [▼
  45. 0 => array:2 [▼
  46. "src" => "XSS 安全漏洞"
  47. "dst" => "XSS security vulnerability"
  48. ]
  49. ]
  50. ]
  51. **/
  52. // 尝试获取获取翻译结果
  53. if (isset($result['trans_result'][0]['dst'])) {
  54. return str_slug($result['trans_result'][0]['dst']);
  55. } else {
  56. // 如果百度翻译没有结果,使用拼音作为后备计划。
  57. return $this->pinyin($text);
  58. }
  59. }
  60. public function pinyin($text)
  61. {
  62. return str_slug(app(Pinyin::class)->permalink($text));
  63. }
  64. }