QrCodeGenerator.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: shenyang
  5. * Date: 2018/12/22
  6. * Time: 3:50 PM
  7. */
  8. namespace app\common\modules\qrCode;
  9. use app\common\exceptions\ShopException;
  10. use SimpleSoftwareIO\QrCode\BaconQrCodeGenerator;
  11. /**
  12. * 解决了下面的问题
  13. * 临时二维码生成慢
  14. * 自动生成目录
  15. * 返回url全路径和文件全路径
  16. * Class QrCodeGenerator
  17. * @package app\common\modules\qrCode
  18. */
  19. class QrCodeGenerator extends BaconQrCodeGenerator
  20. {
  21. /**
  22. * 从缓存中读取二维码内容
  23. * @param $text
  24. * @return mixed
  25. */
  26. public function cache($text,$time = 10080)
  27. {
  28. // 以内容的md5作为key名
  29. $key = md5($text.'v=1');
  30. if (!\Cache::has('qrcode' . '/' . $key)) {
  31. // 二维码内容在缓存中保存一星期
  32. \Cache::put('qrcode' . '/' . $key, $this->generate($text), $time);
  33. }
  34. return \Cache::get('qrcode' . '/' . $key);
  35. }
  36. /**
  37. * 返回二维码url和文件全路径(不存在则生成)
  38. * @param $text
  39. * @param string $path
  40. * @param bool $force 强制重新生成
  41. * @return array
  42. * @throws ShopException
  43. */
  44. public function get($text, $path = 'app/public/qr',$force = false)
  45. {
  46. $name = md5($text.'&salt=2');
  47. if (!is_dir(storage_path($path))) {
  48. self::directory(storage_path($path));
  49. mkdir(storage_path($path), 0777);
  50. }
  51. if (!is_dir(storage_path($path))) {
  52. throw new ShopException('生成二维码目录失败');
  53. }
  54. if (!file_exists(storage_path($path . "/{$name}")) || $force) {
  55. unlink(storage_path($path . "/{$name}"));
  56. // 注意:format方法必须先调用,否则后续方法不生效
  57. $this->format('png')->size(240)->generate($text, storage_path($path . "/{$name}"));
  58. }
  59. if (!file_exists(storage_path($path . "/{$name}"))) {
  60. throw new ShopException('生成二维码失败');
  61. }
  62. if (config('app.framework') == 'platform') {
  63. $urlPath = '';
  64. } else {
  65. $urlPath = '/addons/yun_shop';
  66. }
  67. return [
  68. 'path' => $path . DIRECTORY_SEPARATOR . $name,
  69. 'url' => request()->getSchemeAndHttpHost() . $urlPath . \Storage::url($path . DIRECTORY_SEPARATOR . $name)
  70. ];
  71. }
  72. /**
  73. * 递归生成文件夹
  74. * @param $dir
  75. * @return bool
  76. */
  77. private function directory($dir)
  78. {
  79. return is_dir($dir) or self::directory(dirname($dir)) and mkdir($dir, 0777);
  80. }
  81. }