DotsModule.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. declare(strict_types = 1);
  3. namespace BaconQrCode\Renderer\Module;
  4. use BaconQrCode\Encoder\ByteMatrix;
  5. use BaconQrCode\Exception\InvalidArgumentException;
  6. use BaconQrCode\Renderer\Path\Path;
  7. /**
  8. * Renders individual modules as dots.
  9. */
  10. final class DotsModule implements ModuleInterface
  11. {
  12. public const LARGE = 1;
  13. public const MEDIUM = .8;
  14. public const SMALL = .6;
  15. /**
  16. * @var float
  17. */
  18. private $size;
  19. public function __construct(float $size)
  20. {
  21. if ($size <= 0 || $size > 1) {
  22. throw new InvalidArgumentException('Size must between 0 (exclusive) and 1 (inclusive)');
  23. }
  24. $this->size = $size;
  25. }
  26. public function createPath(ByteMatrix $matrix) : Path
  27. {
  28. $width = $matrix->getWidth();
  29. $height = $matrix->getHeight();
  30. $path = new Path();
  31. $halfSize = $this->size / 2;
  32. $margin = (1 - $this->size) / 2;
  33. for ($y = 0; $y < $height; ++$y) {
  34. for ($x = 0; $x < $width; ++$x) {
  35. if (! $matrix->get($x, $y)) {
  36. continue;
  37. }
  38. $pathX = $x + $margin;
  39. $pathY = $y + $margin;
  40. $path = $path
  41. ->move($pathX + $this->size, $pathY + $halfSize)
  42. ->ellipticArc($halfSize, $halfSize, 0, false, true, $pathX + $halfSize, $pathY + $this->size)
  43. ->ellipticArc($halfSize, $halfSize, 0, false, true, $pathX, $pathY + $halfSize)
  44. ->ellipticArc($halfSize, $halfSize, 0, false, true, $pathX + $halfSize, $pathY)
  45. ->ellipticArc($halfSize, $halfSize, 0, false, true, $pathX + $this->size, $pathY + $halfSize)
  46. ->close()
  47. ;
  48. }
  49. }
  50. return $path;
  51. }
  52. }