1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Overblog\GraphQLBundle\Util; |
6
|
|
|
|
7
|
|
|
final class Base64Encoder |
8
|
|
|
{ |
9
|
101 |
|
public static function encode(string $value): string |
10
|
|
|
{ |
11
|
101 |
|
return \base64_encode($value); |
12
|
|
|
} |
13
|
|
|
|
14
|
62 |
|
public static function decode(string $value, bool $strict = true): string |
15
|
|
|
{ |
16
|
62 |
|
$result = \base64_decode($value, $strict); |
17
|
|
|
|
18
|
62 |
|
if (false === $result) { |
19
|
1 |
|
throw new \InvalidArgumentException(\sprintf('The "%s" value failed to be decoded from base64 format.', $value)); |
20
|
|
|
} |
21
|
|
|
|
22
|
61 |
|
return $result; |
23
|
|
|
} |
24
|
|
|
|
25
|
22 |
|
public static function encodeUrlSafe(string $value, bool $padding = false): string |
26
|
|
|
{ |
27
|
22 |
|
$result = \base64_encode($value); |
28
|
22 |
|
$result = \str_replace(['+', '/'], ['-', '_'], $result); |
29
|
|
|
|
30
|
22 |
|
if (!$padding) { |
31
|
16 |
|
$result = \str_replace('=', '', $result); |
32
|
|
|
} |
33
|
|
|
|
34
|
22 |
|
return $result; |
35
|
|
|
} |
36
|
|
|
|
37
|
24 |
|
public static function decodeUrlSafe(string $value, bool $strict = true): string |
38
|
|
|
{ |
39
|
24 |
|
$value = \str_replace(['-', '_'], ['+', '/'], $value); |
40
|
|
|
|
41
|
24 |
|
if (0 === \substr_compare($value, '=', -1) && 0 !== \strlen($value) % 4) { |
42
|
1 |
|
$value = \str_pad($value, (\strlen($value) + 3) & ~3, '='); |
43
|
|
|
} |
44
|
|
|
|
45
|
24 |
|
$result = \base64_decode($value, $strict); |
46
|
|
|
|
47
|
24 |
|
if (false === $result) { |
48
|
1 |
|
throw new \InvalidArgumentException(\sprintf('The "%s" value failed to be decoded from base64 format.', $value)); |
49
|
|
|
} |
50
|
|
|
|
51
|
23 |
|
return $result; |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|