DataInterfaceTestAbstract.php 8.8 KB

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