Skip to content

Commit

Permalink
feat: add encode util - base64 url
Browse files Browse the repository at this point in the history
  • Loading branch information
kocoten1992 committed May 31, 2022
1 parent 626b493 commit 47cb4a4
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/EncodeUtil.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace Talmp\Phputils;

class EncodeUtil
{
# https://www.php.net/manual/en/function.base64-encode.php
# see in php comment section
public static function base64EncodeUrl(string $string): string
{
return str_replace(['+','/','='], ['-','_',''], base64_encode($string));
}

# https://www.php.net/manual/en/function.base64-encode.php
# see in php comment section
public static function base64DecodeUrl(string $string): string
{
return base64_decode(str_replace(['-','_'], ['+','/'], $string));
}
}
22 changes: 22 additions & 0 deletions tests/EncodeUtilTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

use PHPUnit\Framework\TestCase;
use Talmp\Phputils\EncodeUtil;

class EncodeUtilTest extends TestCase
{
public function test_base64_encode_decode_url()
{
$string = bin2hex(openssl_random_pseudo_bytes(rand(100, 200)));

$encoded_str = EncodeUtil::base64EncodeUrl($string);

$this->assertFalse(str_contains($encoded_str, '+'));
$this->assertFalse(str_contains($encoded_str, '/'));
$this->assertFalse(str_contains($encoded_str, '='));

$decoded_str = EncodeUtil::base64DecodeUrl($encoded_str);

$this->assertEquals($string, $decoded_str);
}
}

0 comments on commit 47cb4a4

Please sign in to comment.