Skip to content

Commit

Permalink
Fix Shift-JIS Error
Browse files Browse the repository at this point in the history
This will fix the issue #123
  • Loading branch information
askdkc committed Mar 19, 2024
1 parent 151a958 commit 04a7339
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
16 changes: 11 additions & 5 deletions src/Encoder/Encoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down
10 changes: 5 additions & 5 deletions test/Encoder/EncoderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
}

Expand Down

0 comments on commit 04a7339

Please sign in to comment.