QRCodeReaderTestAbstract.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. <?php
  2. /**
  3. * Class QRCodeReaderTestAbstract
  4. *
  5. * @created 17.01.2021
  6. * @author Smiley <smiley@chillerlan.net>
  7. * @copyright 2021 Smiley
  8. * @license MIT
  9. *
  10. * @noinspection PhpComposerExtensionStubsInspection
  11. */
  12. declare(strict_types=1);
  13. namespace chillerlan\QRCodeTest;
  14. use chillerlan\QRCode\{QRCode, QROptions};
  15. use chillerlan\QRCode\Common\{EccLevel, LuminanceSourceInterface, Mode, Version};
  16. use chillerlan\QRCode\Decoder\Decoder;
  17. use chillerlan\QRCode\Output\QRGdImagePNG;
  18. use chillerlan\Settings\SettingsContainerInterface;
  19. use PHPUnit\Framework\Attributes\{DataProvider, Group};
  20. use PHPUnit\Framework\TestCase;
  21. use Exception, Generator;
  22. use RuntimeException;
  23. use function array_map, defined, realpath, sprintf, str_repeat, substr;
  24. /**
  25. * Tests the QR Code reader
  26. */
  27. abstract class QRCodeReaderTestAbstract extends TestCase{
  28. use QRMaxLengthTrait, QRMatrixDebugTrait;
  29. /** @see https://www.bobrosslipsum.com/ */
  30. protected const loremipsum = 'Just let this happen. We just let this flow right out of our minds. '
  31. .'Anyone can paint. We touch the canvas, the canvas takes what it wants. From all of us here, '
  32. .'I want to wish you happy painting and God bless, my friends. A tree cannot be straight if it has a crooked trunk. '
  33. .'You have to make almighty decisions when you\'re the creator. I guess that would be considered a UFO. '
  34. .'A big cotton ball in the sky. I\'m gonna add just a tiny little amount of Prussian Blue. '
  35. .'They say everything looks better with odd numbers of things. But sometimes I put even numbers—just '
  36. .'to upset the critics. We\'ll lay all these little funky little things in there. ';
  37. protected const samplesDir = __DIR__.'/samples/';
  38. protected SettingsContainerInterface|QROptions $options;
  39. protected function setUp():void{
  40. $this->options = new QROptions;
  41. $this->options->readerUseImagickIfAvailable = false;
  42. }
  43. /**
  44. * @phpstan-return array<string, array{0: string, 1: string, 2: bool}>
  45. */
  46. public static function qrCodeProvider():array{
  47. return [
  48. 'helloworld' => ['hello_world.png', 'Hello world!', false],
  49. // covers mirroring
  50. 'mirrored' => ['hello_world_mirrored.png', 'Hello world!', false],
  51. // data modes
  52. 'byte' => ['byte.png', 'https://smiley.codes/qrcode/', true],
  53. 'numeric' => ['numeric.png', '123456789012345678901234567890', false],
  54. 'alphanum' => ['alphanum.png', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 $%*+-./:', false],
  55. 'kanji' => ['kanji.png', '茗荷茗荷茗荷茗荷', false],
  56. // covers most of ReedSolomonDecoder
  57. 'damaged' => ['damaged.png', 'https://smiley.codes/qrcode/', false],
  58. // covers attempt to read 2nd (bottom left) version info
  59. 'version2' => ['damaged_version.png', 'https://www.youtube.com/watch?v=dQw4w9WgXcQ', false],
  60. // covers Binarizer::getHistogramBlackMatrix()
  61. 'smol' => ['smol.png', 'https://smiley.codes/qrcode/', false],
  62. // tilted 22° CCW
  63. 'tilted' => ['tilted.png', 'Hello world!', false],
  64. // rotated 90° CW
  65. 'rotated' => ['rotated.png', 'Hello world!', false],
  66. // color gradient (from old svg example)
  67. 'gradient' => ['example_svg.png', 'https://www.youtube.com/watch?v=DLzxrzFCyOs&t=43s', true],
  68. // color gradient (from svg example)
  69. 'dots' => ['example_svg_dots.png', 'https://www.youtube.com/watch?v=dQw4w9WgXcQ', true],
  70. ];
  71. }
  72. abstract protected function getLuminanceSourceFromFile(
  73. string $file,
  74. SettingsContainerInterface|QROptions $options,
  75. ):LuminanceSourceInterface;
  76. #[Group('slow')]
  77. #[DataProvider('qrCodeProvider')]
  78. public function testReader(string $img, string $expected, bool $grayscale):void{
  79. if($grayscale){
  80. $this->options->readerGrayscale = true;
  81. $this->options->readerIncreaseContrast = true;
  82. }
  83. $file = realpath($this::samplesDir.$img);
  84. if($file === false){
  85. throw new RuntimeException(sprintf('invalid file given: "%s" in samples directory "%s"', $img, $this::samplesDir));
  86. }
  87. $luminanceSource = $this->getLuminanceSourceFromFile($file, $this->options);
  88. $result = (new Decoder)->decode($luminanceSource);
  89. $this->debugMatrix($result->getQRMatrix());
  90. $this::assertSame($expected, (string)$result);
  91. }
  92. public function testReaderMultiMode():void{
  93. $this->options->outputInterface = QRGdImagePNG::class;
  94. $this->options->outputBase64 = false;
  95. $numeric = '123456789012345678901234567890';
  96. $alphanum = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 $%*+-./:';
  97. $kanji = '漂う花の香り';
  98. $hanzi = '无可奈何燃花作香';
  99. $byte = 'https://smiley.codes/qrcode/';
  100. $qrcode = (new QRCode($this->options))
  101. ->addNumericSegment($numeric)
  102. ->addAlphaNumSegment($alphanum)
  103. ->addKanjiSegment($kanji)
  104. ->addHanziSegment($hanzi)
  105. ->addByteSegment($byte)
  106. ;
  107. $result = $qrcode->readFromBlob($qrcode->render());
  108. $this::assertSame($numeric.$alphanum.$kanji.$hanzi.$byte, $result->data);
  109. }
  110. public static function dataTestProvider():Generator{
  111. if(!defined('READER_TEST_MAX_VERSION')){
  112. self::markTestSkipped('READER_TEST_MAX_VERSION not defined (see phpunit.xml.dist)');
  113. }
  114. $str = str_repeat(self::loremipsum, 5);
  115. $eccLevels = array_map(fn(int $ecc):EccLevel => new EccLevel($ecc), [EccLevel::L, EccLevel::M, EccLevel::Q, EccLevel::H]);
  116. /** @noinspection PhpUndefinedConstantInspection - see phpunit.xml.dist */
  117. for($v = 1; $v <= READER_TEST_MAX_VERSION; $v++){
  118. $version = new Version($v);
  119. foreach($eccLevels as $eccLevel){
  120. yield 'version: '.$version.$eccLevel => [
  121. $version,
  122. $eccLevel,
  123. substr($str, 0, self::getMaxLengthForMode(Mode::BYTE, $version, $eccLevel)),
  124. ];
  125. }
  126. }
  127. }
  128. #[Group('slow')]
  129. #[DataProvider('dataTestProvider')]
  130. public function testReadData(Version $version, EccLevel $ecc, string $expected):void{
  131. $this->options->outputInterface = QRGdImagePNG::class;
  132. $this->options->imageTransparent = false;
  133. $this->options->eccLevel = $ecc->getLevel();
  134. $this->options->version = $version->getVersionNumber();
  135. $this->options->outputBase64 = false;
  136. // what's interesting is that a smaller scale seems to produce fewer reader errors???
  137. // usually from version 20 up, independend of the luminance source
  138. // scale 1-2 produces none, scale 3: 1 error, scale 4: 6 errors, scale 5: 5 errors, scale 10: 10 errors
  139. // @see \chillerlan\QRCode\Detector\GridSampler::checkAndNudgePoints()
  140. $this->options->scale = 2;
  141. try{
  142. $qrcode = new QRCode($this->options);
  143. $imagedata = $qrcode->render($expected);
  144. $result = $qrcode->readFromBlob($imagedata);
  145. }
  146. catch(Exception $e){
  147. $this::markTestSkipped(sprintf('skipped version %s%s: %s', $version, $ecc, $e->getMessage()));
  148. }
  149. $this::assertSame($expected, $result->data);
  150. $this::assertSame($version->getVersionNumber(), $result->version->getVersionNumber());
  151. $this::assertSame($ecc->getLevel(), $result->eccLevel->getLevel());
  152. }
  153. }