QrCodeHelper.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: shenyang
  5. * Date: 2017/9/26
  6. * Time: 上午11:55
  7. */
  8. namespace app\common\helpers;
  9. use app\common\exceptions\ShopException;
  10. class QrCodeHelper
  11. {
  12. private $patch;
  13. private $url;
  14. private $fileName;
  15. /**
  16. * QrCodeHelper constructor.
  17. * @param $url
  18. * @param $patch
  19. * @throws ShopException
  20. */
  21. function __construct($url, $patch)
  22. {
  23. $this->patch = $patch;
  24. $this->url = $url;
  25. $this->fileName = $this->getFileName();
  26. }
  27. public function filePath()
  28. {
  29. return "$this->patch/{$this->fileName}.png";
  30. }
  31. public function url()
  32. {
  33. return request()->getSchemeAndHttpHost() . config('app.webPath') . \Storage::url($this->patch . "/{$this->fileName}.png");
  34. }
  35. /**
  36. * @return string
  37. * @throws ShopException
  38. */
  39. private function getFileName()
  40. {
  41. $name = md5($this->url);
  42. if (!is_dir(storage_path($this->patch))) {
  43. self::directory(storage_path($this->patch));
  44. mkdir(storage_path($this->patch), 0777);
  45. }
  46. if (!is_dir(storage_path($this->patch))) {
  47. throw new ShopException('生成二维码目录失败');
  48. }
  49. if (!file_exists(storage_path($this->patch . "/{$name}.png")) || request()->input('new')) {
  50. unlink(storage_path($this->patch . "/{$name}.png"));
  51. // 注意:format方法必须先调用,否则后续方法不生效
  52. \QrCode::format('png')->size(300)->generate($this->url, storage_path($this->patch . "/{$name}.png"));
  53. }
  54. if (!file_exists(storage_path($this->patch . "/{$name}.png"))) {
  55. throw new ShopException('生成二维码失败');
  56. }
  57. return $name;
  58. }
  59. private function directory($dir)
  60. {
  61. return is_dir($dir) or self::directory(dirname($dir)) and mkdir($dir, 0777);
  62. }
  63. }