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. namespace chillerlan\QRCodeTest\Data;
  11. use chillerlan\QRCode\Data\Hanzi;
  12. use chillerlan\QRCode\Data\QRDataModeInterface;
  13. use PHPUnit\Framework\Attributes\DataProvider;
  14. use PHPUnit\Framework\Attributes\Group;
  15. use Generator, Throwable;
  16. use function bin2hex, chr, defined, sprintf;
  17. /**
  18. * Tests the Hanzi/GB2312 class
  19. */
  20. final class HanziTest extends DataInterfaceTestAbstract{
  21. protected const testData = '无可奈何燃花作香';
  22. protected static function getDataModeInterface(string $data):QRDataModeInterface{
  23. return new Hanzi($data);
  24. }
  25. /**
  26. * isGB2312() should pass on Hanzi/GB2312 characters and fail on everything else
  27. *
  28. * @phpstan-return array<int, array{0: string, 1: bool}>
  29. */
  30. public static function stringValidateProvider():array{
  31. return [
  32. ['原神', true],
  33. ['ABC', false],
  34. ['123', false],
  35. ['无可奈何燃花作香', true], // https://genshin-impact.fandom.com/wiki/Floral_Incense
  36. ['無可奈何燃花作香', false], // same as above in traditional Chinese
  37. ['꽃잎 향초의 기도', false], // same as above in Korean
  38. ];
  39. }
  40. /**
  41. * lists all characters in the valid GB2312 range
  42. */
  43. public static function hanziProvider():Generator{
  44. for($byte1 = 0xa1; $byte1 < 0xf8; $byte1++){
  45. if($byte1 > 0xa9 && $byte1 < 0xb0){
  46. continue;
  47. }
  48. for($byte2 = 0xa1; $byte2 < 0xff; $byte2++){
  49. $chr = mb_convert_encoding(chr($byte1).chr($byte2), 'UTF-8', Hanzi::ENCODING);
  50. if($chr === '?'){ // skip unknown glyphs
  51. continue;
  52. }
  53. yield sprintf('0x%X', (($byte1 << 8) | $byte2)) => [$chr];
  54. }
  55. }
  56. }
  57. #[Group('slow')]
  58. #[DataProvider('hanziProvider')]
  59. public function testValidateGB2312(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 $e){
  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. }