EndroidQrCodeProvider.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace RobThree\Auth\Providers\Qr;
  3. use Endroid\QrCode\ErrorCorrectionLevel;
  4. use Endroid\QrCode\QrCode;
  5. class EndroidQrCodeProvider implements IQRCodeProvider
  6. {
  7. public $bgcolor;
  8. public $color;
  9. public $margin;
  10. public $errorcorrectionlevel;
  11. public function __construct($bgcolor = 'ffffff', $color = '000000', $margin = 0, $errorcorrectionlevel = 'H')
  12. {
  13. $this->bgcolor = $this->handleColor($bgcolor);
  14. $this->color = $this->handleColor($color);
  15. $this->margin = $margin;
  16. $this->errorcorrectionlevel = $this->handleErrorCorrectionLevel($errorcorrectionlevel);
  17. }
  18. public function getMimeType()
  19. {
  20. return 'image/png';
  21. }
  22. public function getQRCodeImage($qrtext, $size)
  23. {
  24. return $this->qrCodeInstance($qrtext, $size)->writeString();
  25. }
  26. protected function qrCodeInstance($qrtext, $size)
  27. {
  28. $qrCode = new QrCode($qrtext);
  29. $qrCode->setSize($size);
  30. $qrCode->setErrorCorrectionLevel($this->errorcorrectionlevel);
  31. $qrCode->setMargin($this->margin);
  32. $qrCode->setBackgroundColor($this->bgcolor);
  33. $qrCode->setForegroundColor($this->color);
  34. return $qrCode;
  35. }
  36. private function handleColor($color)
  37. {
  38. $split = str_split($color, 2);
  39. $r = hexdec($split[0]);
  40. $g = hexdec($split[1]);
  41. $b = hexdec($split[2]);
  42. return ['r' => $r, 'g' => $g, 'b' => $b, 'a' => 0];
  43. }
  44. private function handleErrorCorrectionLevel($level)
  45. {
  46. switch ($level) {
  47. case 'L':
  48. return ErrorCorrectionLevel::LOW();
  49. case 'M':
  50. return ErrorCorrectionLevel::MEDIUM();
  51. case 'Q':
  52. return ErrorCorrectionLevel::QUARTILE();
  53. case 'H':
  54. return ErrorCorrectionLevel::HIGH();
  55. default:
  56. return ErrorCorrectionLevel::HIGH();
  57. }
  58. }
  59. }