1 | <?php |
||
10 | class Base64 |
||
11 | { |
||
12 | /** |
||
13 | * Encode a string using base64url variant. |
||
14 | * |
||
15 | * @see https://en.wikipedia.org/wiki/Base64#URL_applications |
||
16 | * |
||
17 | * @param string $data |
||
18 | * |
||
19 | * @return string |
||
20 | */ |
||
21 | 170 | public static function urlEncode(string $data): string |
|
24 | } |
||
25 | |||
26 | /** |
||
27 | * Decode a string using base64url variant. |
||
28 | * |
||
29 | * @see https://en.wikipedia.org/wiki/Base64#URL_applications |
||
30 | * |
||
31 | * @param string $data |
||
32 | * |
||
33 | * @throws \UnexpectedValueException |
||
34 | * |
||
35 | * @return string |
||
36 | */ |
||
37 | 130 | public static function urlDecode(string $data): string |
|
38 | { |
||
39 | 130 | $data = strtr($data, '-_', '+/'); |
|
40 | 130 | switch (strlen($data) % 4) { |
|
41 | 130 | case 0: |
|
42 | 78 | break; |
|
43 | 112 | case 2: |
|
44 | 80 | $data .= '=='; |
|
45 | 80 | break; |
|
46 | 68 | case 3: |
|
47 | 67 | $data .= '='; |
|
48 | 67 | break; |
|
49 | default: |
||
50 | 1 | throw new \UnexpectedValueException( |
|
51 | 1 | 'Malformed base64url encoding.'); |
|
52 | } |
||
53 | 129 | return self::decode($data); |
|
54 | } |
||
55 | |||
56 | /** |
||
57 | * Check whether string is validly base64url encoded. |
||
58 | * |
||
59 | * @see https://en.wikipedia.org/wiki/Base64#URL_applications |
||
60 | * |
||
61 | * @param string $data |
||
62 | * |
||
63 | * @return bool |
||
64 | */ |
||
65 | 141 | public static function isValidURLEncoding(string $data): bool |
|
68 | } |
||
69 | |||
70 | /** |
||
71 | * Encode a string in base64. |
||
72 | * |
||
73 | * @see https://tools.ietf.org/html/rfc4648#section-4 |
||
74 | * |
||
75 | * @param string $data |
||
76 | * |
||
77 | * @return string |
||
78 | */ |
||
79 | 173 | public static function encode(string $data): string |
|
82 | } |
||
83 | |||
84 | /** |
||
85 | * Decode a string from base64 encoding. |
||
86 | * |
||
87 | * @see https://tools.ietf.org/html/rfc4648#section-4 |
||
88 | * |
||
89 | * @param string $data |
||
90 | * |
||
91 | * @throws \RuntimeException If decoding fails |
||
92 | * |
||
93 | * @return string |
||
94 | */ |
||
95 | 131 | public static function decode(string $data): string |
|
104 | } |
||
105 | |||
106 | /** |
||
107 | * Check whether string is validly base64 encoded. |
||
108 | * |
||
109 | * @see https://tools.ietf.org/html/rfc4648#section-4 |
||
110 | * |
||
111 | * @param string $data |
||
112 | * |
||
113 | * @return bool |
||
120 |