Skip to content

Commit 88ca882

Browse files
Merge pull request #15 from fkooman/add-encodeUnpadded
implement Base64::encodeUnpadded for v1.x
2 parents 129f4cf + 0478b33 commit 88ca882

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed

src/Base64.php

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,29 @@ abstract class Base64 implements EncoderInterface
4141
* @return string
4242
*/
4343
public static function encode($src)
44+
{
45+
return static::doEncode($src, \true);
46+
}
47+
48+
/**
49+
* Encode into Base64, no = padding
50+
*
51+
* Base64 character set "[A-Z][a-z][0-9]+/"
52+
*
53+
* @param string $src
54+
* @return string
55+
*/
56+
public static function encodeUnpadded($src)
57+
{
58+
return static::doEncode($src, \false);
59+
}
60+
61+
/**
62+
* @param string $src
63+
* @param bool $pad Include = padding?
64+
* @return string
65+
*/
66+
protected static function doEncode($src, $pad = \true)
4467
{
4568
$dest = '';
4669
$srcLen = Binary::safeStrlen($src);
@@ -66,11 +89,17 @@ public static function encode($src)
6689
$dest .=
6790
static::encode6Bits( $b0 >> 2 ) .
6891
static::encode6Bits((($b0 << 4) | ($b1 >> 4)) & 63) .
69-
static::encode6Bits( ($b1 << 2) & 63) . '=';
92+
static::encode6Bits( ($b1 << 2) & 63);
93+
if ($pad) {
94+
$dest .= '=';
95+
}
7096
} else {
7197
$dest .=
7298
static::encode6Bits( $b0 >> 2) .
73-
static::encode6Bits(($b0 << 4) & 63) . '==';
99+
static::encode6Bits(($b0 << 4) & 63);
100+
if ($pad) {
101+
$dest .= '==';
102+
}
74103
}
75104
}
76105
return $dest;

tests/Base64UrlSafeTest.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,15 @@ public function testRandom()
2222
\strtr(\base64_encode($random), '+/', '-_'),
2323
$enc
2424
);
25-
25+
$unpadded = \rtrim($enc, '=');
26+
$this->assertSame(
27+
$unpadded,
28+
Base64UrlSafe::encodeUnpadded($random)
29+
);
30+
$this->assertSame(
31+
$random,
32+
Base64UrlSafe::decode($unpadded)
33+
);
2634
}
2735
}
2836
}

0 commit comments

Comments
 (0)