DataInterfaceTestAbstract.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. <?php
  2. /**
  3. * Class DataInterfaceTestAbstract
  4. *
  5. * @created 24.11.2017
  6. * @author Smiley <smiley@chillerlan.net>
  7. * @copyright 2017 Smiley
  8. * @license MIT
  9. */
  10. declare(strict_types=1);
  11. namespace chillerlan\QRCodeTest\Data;
  12. use chillerlan\QRCode\Common\{BitBuffer, EccLevel, MaskPattern, Mode, Version};
  13. use chillerlan\QRCode\Data\{QRCodeDataException, QRData, QRDataModeInterface, QRMatrix};
  14. use chillerlan\QRCode\QROptions;
  15. use chillerlan\QRCodeTest\Traits\QRMaxLengthTrait;
  16. use Exception, Generator;
  17. use PHPUnit\Framework\Attributes\DataProvider;
  18. use PHPUnit\Framework\ExpectationFailedException;
  19. use PHPUnit\Framework\TestCase;
  20. use function array_map, hex2bin, mb_strlen, mb_substr, sprintf, str_repeat, strlen, substr;
  21. /**
  22. * The data interface test abstract
  23. */
  24. abstract class DataInterfaceTestAbstract extends TestCase{
  25. use QRMaxLengthTrait;
  26. protected QRData $QRData;
  27. protected QRDataModeInterface $dataMode;
  28. protected const testData = '';
  29. protected function setUp():void{
  30. $this->QRData = new QRData(new QROptions);
  31. $this->dataMode = static::getDataModeInterface(static::testData);
  32. }
  33. abstract protected static function getDataModeInterface(string $data):QRDataModeInterface;
  34. /**
  35. * @return int[][]
  36. */
  37. public static function maskPatternProvider():array{
  38. return [[0], [1], [2], [3], [4], [5], [6], [7]];
  39. }
  40. /**
  41. * Tests initializing the data matrix
  42. */
  43. #[DataProvider('maskPatternProvider')]
  44. public function testInitMatrix(int $pattern):void{
  45. $maskPattern = new MaskPattern($pattern);
  46. $this->QRData->setData([$this->dataMode]);
  47. $matrix = $this->QRData->writeMatrix()->setFormatInfo($maskPattern)->mask($maskPattern);
  48. $this::assertInstanceOf(QRMatrix::class, $matrix);
  49. $this::assertSame($pattern, $matrix->getMaskPattern()->getPattern());
  50. }
  51. /**
  52. * @phpstan-return array<int, array{0: string, 1: bool}>
  53. */
  54. abstract public static function stringValidateProvider():array;
  55. /**
  56. * Tests if a string is properly validated for the respective data mode
  57. */
  58. #[DataProvider('stringValidateProvider')]
  59. public function testValidateString(string $string, bool $expected):void{
  60. $this::assertSame($expected, $this->dataMode::validateString($string));
  61. // back out on potentially invalid strings
  62. if($expected === false){
  63. return;
  64. }
  65. $dataModeInterface = static::getDataModeInterface($string);
  66. $bitBuffer = new BitBuffer;
  67. // check if the validated string encodes without error
  68. // https://github.com/chillerlan/php-qrcode/pull/313
  69. $dataModeInterface->write($bitBuffer, 40);
  70. $bitBuffer->rewind();
  71. // read 4 bits (data mode indicator)
  72. $bitBuffer->read(4);
  73. // decode and check against the given string
  74. $decoded = $dataModeInterface::decodeSegment($bitBuffer, 40);
  75. $this::assertSame($string, $decoded);
  76. }
  77. /**
  78. * Tests if a random binary string is properly validated as false
  79. *
  80. * @see https://github.com/chillerlan/php-qrcode/issues/182
  81. */
  82. public function testBinaryStringInvalid():void{
  83. $this::assertFalse($this->dataMode::validateString(hex2bin('01015989f47dff8e852122117e04c90b9f15defc1c36477b1fe1')));
  84. }
  85. /**
  86. * returns versions within the version breakpoints 1-9, 10-26 and 27-40
  87. *
  88. * @phpstan-return array<string, array{0: int}>
  89. */
  90. public static function versionBreakpointProvider():array{
  91. return ['1-9' => [7], '10-26' => [15], '27-40' => [30]];
  92. }
  93. /**
  94. * Tests decoding a data segment from a given BitBuffer
  95. */
  96. #[DataProvider('versionBreakpointProvider')]
  97. public function testDecodeSegment(int $version):void{
  98. $options = new QROptions;
  99. $options->version = $version;
  100. // invoke a QRData instance and write data
  101. $this->QRData = new QRData($options, [$this->dataMode]);
  102. // get the filled bitbuffer
  103. $bitBuffer = $this->QRData->getBitBuffer();
  104. // read the first 4 bits
  105. $this::assertSame($this->dataMode::DATAMODE, $bitBuffer->read(4));
  106. // decode the data
  107. $this::assertSame(static::testData, $this->dataMode::decodeSegment($bitBuffer, $options->version));
  108. }
  109. /**
  110. * Generates test data for each data mode:
  111. *
  112. * - version
  113. * - ECC level
  114. * - a string that contains the maximum amount of characters for the given mode
  115. * - a string that contains characters for the given mode and that exceeds the maximum length by one/two character(s)
  116. * - the maximum allowed character length
  117. *
  118. * @throws \Exception
  119. */
  120. public static function maxLengthProvider():Generator{
  121. $eccLevels = array_map(fn(int $ecc):EccLevel => new EccLevel($ecc), [EccLevel::L, EccLevel::M, EccLevel::Q, EccLevel::H]);
  122. $str = str_repeat(static::testData, 1000);
  123. /** @phan-suppress-next-line PhanAbstractStaticMethodCallInStatic */
  124. $dataMode = static::getDataModeInterface(static::testData)::DATAMODE;
  125. $mb = ($dataMode === Mode::KANJI || $dataMode === Mode::HANZI);
  126. for($v = 1; $v <= 40; $v++){
  127. $version = new Version($v);
  128. foreach($eccLevels as $eccLevel){
  129. // maximum characters per ecc/mode
  130. $len = static::getMaxLengthForMode($dataMode, $version, $eccLevel);
  131. // a string that contains the maximum amount of characters for the given mode
  132. $val = ($mb) ? mb_substr($str, 0, $len) : substr($str, 0, $len);
  133. // same as above but character count exceeds
  134. // kanji/hanzi may have space for a single character, so we add 2 to make sure we exceed
  135. $val1 = ($mb) ? mb_substr($str, 0, ($len + 2)) : substr($str, 0, ($len + 1));
  136. // array key
  137. $key = sprintf('version: %s%s (%s)', $version, $eccLevel, $len);
  138. if((($mb) ? mb_strlen($val) : strlen($val)) !== $len){
  139. throw new Exception('output length does not match');
  140. }
  141. yield $key => [$version, $eccLevel, $val, $val1, $len];
  142. }
  143. }
  144. }
  145. #[DataProvider('maxLengthProvider')]
  146. public function testMaxLength(Version $version, EccLevel $eccLevel, string $str):void{
  147. $options = new QROptions;
  148. $options->version = $version->getVersionNumber();
  149. $options->eccLevel = $eccLevel->getLevel();
  150. $this->dataMode = static::getDataModeInterface($str);
  151. $this->QRData = new QRData($options, [$this->dataMode]);
  152. $bitBuffer = $this->QRData->getBitBuffer();
  153. $this::assertSame($this->dataMode::DATAMODE, $bitBuffer->read(4));
  154. $this::assertSame($str, $this->dataMode::decodeSegment($bitBuffer, $options->version));
  155. }
  156. /**
  157. * Tests getting the minimum QR version for the given data
  158. */
  159. #[DataProvider('maxLengthProvider')]
  160. public function testGetMinimumVersion(Version $version, EccLevel $eccLevel, string $str):void{
  161. $options = new QROptions;
  162. $options->version = Version::AUTO;
  163. $options->eccLevel = $eccLevel->getLevel();
  164. $this->dataMode = static::getDataModeInterface($str);
  165. $this->QRData = new QRData($options, [$this->dataMode]);
  166. $bitBuffer = $this->QRData->getBitBuffer();
  167. $this::assertLessThanOrEqual($eccLevel->getMaxBitsForVersion($version), $this->QRData->estimateTotalBitLength());
  168. $minimumVersionNumber = $this->QRData->getMinimumVersion()->getVersionNumber();
  169. try{
  170. $this::assertSame($version->getVersionNumber(), $minimumVersionNumber);
  171. }
  172. catch(ExpectationFailedException){
  173. $this::assertSame(($version->getVersionNumber() + 1), $minimumVersionNumber, 'safety margin');
  174. }
  175. // verify the encoded data
  176. $this::assertSame($this->dataMode::DATAMODE, $bitBuffer->read(4));
  177. $this::assertSame($str, $this->dataMode::decodeSegment($bitBuffer, $minimumVersionNumber));
  178. }
  179. /**
  180. * Tests if an exception is thrown on data overflow
  181. */
  182. #[DataProvider('maxLengthProvider')]
  183. public function testMaxLengthOverflowException(Version $version, EccLevel $eccLevel, string $str, string $str1):void{
  184. $this->expectException(QRCodeDataException::class);
  185. $this->expectExceptionMessage('code length overflow');
  186. $options = new QROptions;
  187. $options->version = $version->getVersionNumber();
  188. $options->eccLevel = $eccLevel->getLevel();
  189. new QRData($options, [static::getDataModeInterface($str1)]);
  190. }
  191. /**
  192. * Tests if an exception is thrown when the data exceeds the maximum version while auto-detecting
  193. */
  194. public function testGetMinimumVersionException():void{
  195. $this->expectException(QRCodeDataException::class);
  196. $this->expectExceptionMessage('data exceeds');
  197. $this->QRData->setData([static::getDataModeInterface(str_repeat(static::testData, 1337))]);
  198. }
  199. /**
  200. * Tests if an exception is thrown when an invalid character is encountered
  201. */
  202. public function testInvalidDataException():void{
  203. $this->expectException(QRCodeDataException::class);
  204. $this->expectExceptionMessage('invalid data');
  205. static::getDataModeInterface('##');
  206. }
  207. /**
  208. * Tests if an exception is thrown if the given string is empty
  209. */
  210. public function testInvalidDataOnEmptyException():void{
  211. $this->expectException(QRCodeDataException::class);
  212. $this->expectExceptionMessage('invalid data');
  213. static::getDataModeInterface('');
  214. }
  215. }