HanziTest.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. public static function stringValidateProvider():array{
  29. return [
  30. ['原神', true],
  31. ['ABC', false],
  32. ['123', false],
  33. ['无可奈何燃花作香', true], // https://genshin-impact.fandom.com/wiki/Floral_Incense
  34. ['無可奈何燃花作香', false], // same as above in traditional Chinese
  35. ['꽃잎 향초의 기도', false], // same as above in Korean
  36. ];
  37. }
  38. /**
  39. * lists all characters in the valid GB2312 range
  40. */
  41. public static function hanziProvider():Generator{
  42. for($byte1 = 0xa1; $byte1 < 0xf8; $byte1++){
  43. if($byte1 > 0xa9 && $byte1 < 0xb0){
  44. continue;
  45. }
  46. for($byte2 = 0xa1; $byte2 < 0xff; $byte2++){
  47. $chr = mb_convert_encoding(chr($byte1).chr($byte2), 'UTF-8', Hanzi::ENCODING);
  48. if($chr === '?'){ // skip unknown glyphs
  49. continue;
  50. }
  51. yield sprintf('0x%X', (($byte1 << 8) | $byte2)) => [$chr];
  52. }
  53. }
  54. }
  55. #[Group('slow')]
  56. #[DataProvider('hanziProvider')]
  57. public function testValidateGB2312(string $chr):void{
  58. // we may run into several issues due to encoding detection failures
  59. try{
  60. $this::assertTrue(Hanzi::validateString($chr));
  61. }
  62. catch(Throwable $e){
  63. /** @noinspection PhpUndefinedConstantInspection - see phpunit.xml.dist */
  64. if(defined('TEST_IS_CI') && TEST_IS_CI === true){
  65. $this::markTestSkipped();
  66. }
  67. $this::markTestSkipped(sprintf(
  68. 'invalid glyph: %s => %s',
  69. bin2hex(mb_convert_encoding($chr, Hanzi::ENCODING, 'UTF-8')),
  70. $chr
  71. ));
  72. }
  73. }
  74. }