Skip to content

Commit 1f58787

Browse files
committed
Improve implementation
1 parent 0c37300 commit 1f58787

File tree

1 file changed

+19
-14
lines changed

1 file changed

+19
-14
lines changed

Diff for: src/Base32/Base32.php

+19-14
Original file line numberDiff line numberDiff line change
@@ -102,20 +102,13 @@ public function decode(string $encoded, bool $strict = false): string
102102
$encoded = strtoupper($encoded);
103103
}
104104

105-
$remainder = strlen($encoded) % 8;
106-
if (0 !== $remainder) {
107-
if ($strict) {
108-
throw new RuntimeException('The encoded data length is invalid.');
109-
}
110-
111-
$encoded .= str_repeat($padding, $remainder);
112-
}
113-
114105
$inside = rtrim($encoded, $padding);
115106
$end = substr($encoded, strlen($inside));
116-
$endLength = strlen($end);
117-
if ($strict && 0 !== $endLength && 1 !== $endLength && 3 !== $endLength && 4 !== $endLength && 6 !== $endLength) {
118-
throw new RuntimeException('The encoded data ends with an invalid padding sequence length.');
107+
if ($strict) {
108+
$endLength = strlen($end);
109+
if (0 !== $endLength && 1 !== $endLength && 3 !== $endLength && 4 !== $endLength && 6 !== $endLength) {
110+
throw new RuntimeException('The encoded data ends with an invalid padding sequence length.');
111+
}
119112
}
120113

121114
if (false !== strpos($inside, $padding)) {
@@ -126,11 +119,23 @@ public function decode(string $encoded, bool $strict = false): string
126119
$encoded = str_replace($padding, '', $inside).$end;
127120
}
128121

122+
$remainder = strlen($encoded) % 8;
123+
if (0 !== $remainder) {
124+
if ($strict) {
125+
throw new RuntimeException('The encoded data length is invalid.');
126+
}
127+
128+
for ($index = 0; $index < $remainder; $index++) {
129+
$encoded .= $padding;
130+
}
131+
}
132+
129133
$chars = [];
130-
foreach (str_split($alphabet) as $offset => $char) {
131-
$chars[$char] = $offset;
134+
for ($index = 0; $index < self::ALPHABET_SIZE; $index++) {
135+
$chars[$alphabet[$index]] = $index;
132136
}
133137
$chars[$padding] = 0;
138+
134139
$offset = 0;
135140
$bitLen = 5;
136141
$length = strlen($encoded);

0 commit comments

Comments
 (0)