Designer.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace addons\shopro\job;
  3. use think\exception\HttpResponseException;
  4. use think\queue\Job;
  5. use GuzzleHttp\Client;
  6. /**
  7. * 设计师模板图片转存
  8. */
  9. class Designer extends BaseJob
  10. {
  11. protected $client = null;
  12. /**
  13. * 转存
  14. */
  15. public function redeposit(Job $job, $data)
  16. {
  17. // 删除 job,防止这个队列一直异常无法被删除
  18. $job->delete();
  19. try {
  20. $imageList = $data['imageList'];
  21. foreach ($imageList as $image) {
  22. try {
  23. // 路径转存图片,这里只保存到本地 public/storage 目录
  24. $this->redepositSave($image, parse_url($image, PHP_URL_PATH));
  25. } catch (HttpResponseException $e) {
  26. $data = $e->getResponse()->getData();
  27. $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
  28. \think\Log::error('设计师模板图片转存失败-HttpResponseException: ' . $message);
  29. } catch (\Exception $e) {
  30. \think\Log::error('设计师模板图片转存失败: ' . $e->getMessage());
  31. }
  32. }
  33. } catch (HttpResponseException $e) {
  34. $data = $e->getResponse()->getData();
  35. $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
  36. format_log_error($e, 'Designer.redeposit.HttpResponseException', $message);
  37. } catch (\Exception $e) {
  38. // 队列执行失败
  39. format_log_error($e, 'Designer.redeposit');
  40. }
  41. }
  42. /**
  43. * 转存到本地
  44. *
  45. * @param [type] $path
  46. * @param [type] $save_path
  47. * @return void
  48. */
  49. private function redepositSave($path, $save_path)
  50. {
  51. $response = $this->getClient()->get($path);
  52. $body = $response->getBody()->getContents(); // 图片数据流
  53. $save_path = ROOT_PATH . 'public/' . ltrim($save_path, '/');
  54. $save_dir = dirname($save_path);
  55. if (!is_dir($save_dir)) {
  56. @mkdir($save_dir, 0755, true);
  57. }
  58. file_put_contents($save_path, $body); // 转存本地
  59. }
  60. private function getClient()
  61. {
  62. if ($this->client) {
  63. return $this->client;
  64. }
  65. return $this->client = new Client();
  66. }
  67. }