Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 11 additions & 23 deletions src/Encoder/Encoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,11 @@ public static function encode(
$headerAndDataBits->appendBitArray($headerBits);

// Find "length" of main segment and write it.
$numLetters = (Mode::BYTE() === $mode ? $dataBits->getSizeInBytes() : strlen($content));
$numLetters = match ($mode) {
Mode::BYTE() => $dataBits->getSizeInBytes(),
Mode::NUMERIC(), Mode::ALPHANUMERIC() => strlen($content),
Mode::KANJI() => iconv_strlen($content, 'utf-8'),
};
self::appendLengthInfo($numLetters, $version, $mode, $headerAndDataBits);

// Put data together into the overall payload.
Expand Down Expand Up @@ -514,31 +518,15 @@ private static function appendLengthInfo(int $numLetters, Version $version, Mode

/**
* Appends bytes to a bit array in a specific mode.
*
* @throws WriterException if an invalid mode was supplied
*/
private static function appendBytes(string $content, Mode $mode, BitArray $bits, string $encoding) : void
{
switch ($mode) {
case Mode::NUMERIC():
self::appendNumericBytes($content, $bits);
break;

case Mode::ALPHANUMERIC():
self::appendAlphanumericBytes($content, $bits);
break;

case Mode::BYTE():
self::append8BitBytes($content, $bits, $encoding);
break;

case Mode::KANJI():
self::appendKanjiBytes($content, $bits);
break;

default:
throw new WriterException('Invalid mode: ' . $mode);
}
match ($mode) {
Mode::NUMERIC() => self::appendNumericBytes($content, $bits),
Mode::ALPHANUMERIC() => self::appendAlphanumericBytes($content, $bits),
Mode::BYTE() => self::append8BitBytes($content, $bits, $encoding),
Mode::KANJI() => self::appendKanjiBytes($content, $bits),
};
}

/**
Expand Down
6 changes: 6 additions & 0 deletions test/Encoder/EncoderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,12 @@ public function testChooseMode() : void

// Sou-Utso-Byou in Kanji in SHIFT-JIS
$this->assertSame(Mode::BYTE(), $this->methods['chooseMode']->invoke(null, "\xe\x4\x9\x5\x9\x61"));

// SHIFT-JIS encoding, content only consists of double-byte kanji characters
$this->assertSame(Mode::KANJI(), $this->methods['chooseMode']->invoke(null, 'あいうえお', 'SHIFT-JIS'));

// SHIFT-JIS encoding, but content doesn't exclusively consist of kanji characters
$this->assertSame(Mode::BYTE(), $this->methods['chooseMode']->invoke(null, 'あいうえお123', 'SHIFT-JIS'));
}

public function testEncode() : void
Expand Down