Skip to content

Commit

Permalink
Improve implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
nyamsprod committed Mar 26, 2024
1 parent 0c37300 commit ecfca43
Showing 1 changed file with 24 additions and 15 deletions.
39 changes: 24 additions & 15 deletions src/Base32/Base32.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,20 +102,13 @@ public function decode(string $encoded, bool $strict = false): string
$encoded = strtoupper($encoded);
}

$remainder = strlen($encoded) % 8;
if (0 !== $remainder) {
if ($strict) {
throw new RuntimeException('The encoded data length is invalid.');
}

$encoded .= str_repeat($padding, $remainder);
}

$inside = rtrim($encoded, $padding);
$end = substr($encoded, strlen($inside));
$endLength = strlen($end);
if ($strict && 0 !== $endLength && 1 !== $endLength && 3 !== $endLength && 4 !== $endLength && 6 !== $endLength) {
throw new RuntimeException('The encoded data ends with an invalid padding sequence length.');
if ($strict) {
$endLength = strlen($end);
if (0 !== $endLength && 1 !== $endLength && 3 !== $endLength && 4 !== $endLength && 6 !== $endLength) {
throw new RuntimeException('The encoded data ends with an invalid padding sequence length.');
}
}

if (false !== strpos($inside, $padding)) {
Expand All @@ -126,18 +119,34 @@ public function decode(string $encoded, bool $strict = false): string
$encoded = str_replace($padding, '', $inside).$end;
}

$remainder = strlen($encoded) % 8;
if (0 !== $remainder) {
if ($strict) {
throw new RuntimeException('The encoded data length is invalid.');
}

for ($index = 0; $index < $remainder; $index++) {
$encoded .= $padding;
}
}

$chars = [];
foreach (str_split($alphabet) as $offset => $char) {
$chars[$char] = $offset;
for ($index = 0; $index < self::ALPHABET_SIZE; $index++) {
$chars[$alphabet[$index]] = $index;
}
$chars[$padding] = 0;

$offset = 0;
$bitLen = 5;
$length = strlen($encoded);
$decoded = '';

do {
$val ??= $chars[$encoded[$offset]] ?? -1;
if (!isset($val)) {
$index = $encoded[$offset];
$val = array_key_exists($index, $chars) ? $chars[$index] : -1;
}

if (-1 === $val) {
if ($strict) {
throw new RuntimeException('The encoded data contains characters unknown to the base32 alphabet.');
Expand Down

0 comments on commit ecfca43

Please sign in to comment.