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 1f58787
Showing 1 changed file with 19 additions and 14 deletions.
33 changes: 19 additions & 14 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,11 +119,23 @@ 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);
Expand Down

0 comments on commit 1f58787

Please sign in to comment.