HanziTest.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. /**
  3. * Class HanziTest
  4. *
  5. * @created 20.11.2021
  6. * @author smiley <smiley@chillerlan.net>
  7. * @copyright 2021 smiley
  8. * @license MIT
  9. */
  10. declare(strict_types=1);
  11. namespace chillerlan\QRCodeTest\Data;
  12. use chillerlan\QRCode\Data\{Hanzi, QRDataModeInterface};
  13. use PHPUnit\Framework\Attributes\{DataProvider, Group, Test};
  14. use Generator, Throwable;
  15. use function bin2hex, chr, defined, sprintf;
  16. /**
  17. * Tests the Hanzi/GB2312 class
  18. */
  19. final class HanziTest extends DataInterfaceTestAbstract{
  20. protected const testData = '无可奈何燃花作香';
  21. protected static function getDataModeInterface(string $data):QRDataModeInterface{
  22. return new Hanzi($data);
  23. }
  24. /**
  25. * isGB2312() should pass on Hanzi/GB2312 characters and fail on everything else
  26. *
  27. * @phpstan-return array<int, array{0: string, 1: bool}>
  28. */
  29. public static function stringValidateProvider():array{
  30. return [
  31. ['原神', true],
  32. ['ABC', false],
  33. ['123', false],
  34. ['无可奈何燃花作香', true], // https://genshin-impact.fandom.com/wiki/Floral_Incense
  35. ['無可奈何燃花作香', false], // same as above in traditional Chinese
  36. ['꽃잎 향초의 기도', false], // same as above in Korean
  37. ];
  38. }
  39. /**
  40. * lists all characters in the valid GB2312 range
  41. */
  42. public static function hanziProvider():Generator{
  43. for($byte1 = 0xa1; $byte1 < 0xf8; $byte1++){
  44. if($byte1 > 0xa9 && $byte1 < 0xb0){
  45. continue;
  46. }
  47. for($byte2 = 0xa1; $byte2 < 0xff; $byte2++){
  48. $chr = mb_convert_encoding(chr($byte1).chr($byte2), 'UTF-8', Hanzi::ENCODING);
  49. if($chr === '?'){ // skip unknown glyphs
  50. continue;
  51. }
  52. yield sprintf('0x%X', (($byte1 << 8) | $byte2)) => [$chr];
  53. }
  54. }
  55. }
  56. #[Test]
  57. #[Group('slow')]
  58. #[DataProvider('hanziProvider')]
  59. public function validateGB2312(string $chr):void{
  60. // we may run into several issues due to encoding detection failures
  61. try{
  62. $this::assertTrue(Hanzi::validateString($chr));
  63. }
  64. catch(Throwable){
  65. /** @noinspection PhpUndefinedConstantInspection - see phpunit.xml.dist */
  66. if(defined('TEST_IS_CI') && TEST_IS_CI === true){
  67. $this::markTestSkipped();
  68. }
  69. $this::markTestSkipped(sprintf(
  70. 'invalid glyph: %s => %s',
  71. bin2hex(mb_convert_encoding($chr, Hanzi::ENCODING, 'UTF-8')),
  72. $chr,
  73. ));
  74. }
  75. }
  76. }