From 04a7339cd3f64ed43b6378fabab915922ac79adf Mon Sep 17 00:00:00 2001 From: askdkc Date: Tue, 19 Mar 2024 10:55:33 +0900 Subject: [PATCH] Fix Shift-JIS Error This will fix the issue #123 --- src/Encoder/Encoder.php | 16 +++++++++++----- test/Encoder/EncoderTest.php | 10 +++++----- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/Encoder/Encoder.php b/src/Encoder/Encoder.php index 97369fc..b2d460e 100644 --- a/src/Encoder/Encoder.php +++ b/src/Encoder/Encoder.php @@ -222,7 +222,7 @@ private static function isOnlyDoubleByteKanji(string $content) : bool } for ($i = 0; $i < $length; $i += 2) { - $byte = $bytes[$i] & 0xff; + $byte = ord($bytes[$i]) & 0xff; if (($byte < 0x81 || $byte > 0x9f) && $byte < 0xe0 || $byte > 0xeb) { return false; @@ -634,17 +634,23 @@ private static function append8BitBytes(string $content, BitArray $bits, string */ private static function appendKanjiBytes(string $content, BitArray $bits) : void { - if (strlen($content) % 2 > 0) { + $bytes = @iconv('utf-8', 'SHIFT-JIS', $content); + + if (false === $bytes) { + throw new WriterException('Content could not be converted to SHIFT-JIS'); + } + + if (strlen($bytes) % 2 > 0) { // We just do a simple length check here. The for loop will check // individual characters. throw new WriterException('Content does not seem to be encoded in SHIFT-JIS'); } - $length = strlen($content); + $length = strlen($bytes); for ($i = 0; $i < $length; $i += 2) { - $byte1 = ord($content[$i]) & 0xff; - $byte2 = ord($content[$i + 1]) & 0xff; + $byte1 = ord($bytes[$i]) & 0xff; + $byte2 = ord($bytes[$i + 1]) & 0xff; $code = ($byte1 << 8) | $byte2; if ($code >= 0x8140 && $code <= 0x9ffc) { diff --git a/test/Encoder/EncoderTest.php b/test/Encoder/EncoderTest.php index d0839b7..66459e9 100644 --- a/test/Encoder/EncoderTest.php +++ b/test/Encoder/EncoderTest.php @@ -287,11 +287,11 @@ public function testAppendBytes() : void $this->assertSame(' .XX....X .XX...X. .XX...XX', (string) $bits); // Should use appendKanjiBytes. - // 0x93, 0x5f + // 0x93, 0x5f :点 $bits = new BitArray(); $this->methods['appendBytes']->invoke( null, - "\x93\x5f", + '点', Mode::KANJI(), $bits, Encoder::DEFAULT_BYTE_MODE_ENCODING @@ -477,12 +477,12 @@ public function testAppend8BitBytes() : void public function testAppendKanjiBytes() : void { - // Numbers are from page 21 of JISX0510:2004 + // Numbers are from page 21 of JISX0510:2004 点 and 茗 $bits = new BitArray(); - $this->methods['appendKanjiBytes']->invoke(null, "\x93\x5f", $bits); + $this->methods['appendKanjiBytes']->invoke(null, '点', $bits); $this->assertSame(' .XX.XX.. XXXXX', (string) $bits); - $this->methods['appendKanjiBytes']->invoke(null, "\xe4\xaa", $bits); + $this->methods['appendKanjiBytes']->invoke(null, '茗', $bits); $this->assertSame(' .XX.XX.. XXXXXXX. X.X.X.X. X.', (string) $bits); }