DataInterfaceTestAbstract.php 8.8 KB

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