1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Copyright 2015 François Kooman <[email protected]>. |
5
|
|
|
* |
6
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
7
|
|
|
* you may not use this file except in compliance with the License. |
8
|
|
|
* You may obtain a copy of the License at |
9
|
|
|
* |
10
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0 |
11
|
|
|
* |
12
|
|
|
* Unless required by applicable law or agreed to in writing, software |
13
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS, |
14
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
15
|
|
|
* See the License for the specific language governing permissions and |
16
|
|
|
* limitations under the License. |
17
|
|
|
*/ |
18
|
|
|
|
19
|
|
|
namespace fkooman\RemoteStorage\Base64; |
20
|
|
|
|
21
|
|
|
use InvalidArgumentException; |
22
|
|
|
|
23
|
|
|
class Base64 |
24
|
|
|
{ |
25
|
|
|
/** |
26
|
|
|
* Encode to base64. |
27
|
|
|
* |
28
|
|
|
* @param string $data the data to encode |
29
|
|
|
* |
30
|
|
|
* @return string the encoded data |
31
|
|
|
*/ |
32
|
|
|
public static function encode($data) |
33
|
|
|
{ |
34
|
|
|
if (!is_string($data)) { |
35
|
|
|
throw new InvalidArgumentException('data must be string'); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
return base64_encode($data); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Decode base64. |
43
|
|
|
* |
44
|
|
|
* @param string $data the data to decode |
45
|
|
|
* |
46
|
|
|
* @return string the decoded data |
47
|
|
|
*/ |
48
|
|
|
public static function decode($data) |
49
|
|
|
{ |
50
|
|
|
if (!is_string($data)) { |
51
|
|
|
throw new InvalidArgumentException('data must be string'); |
52
|
|
|
} |
53
|
|
|
if (1 === strlen($data) % 4) { |
54
|
|
|
throw new InvalidArgumentException('invalid base64 string length'); |
55
|
|
|
} |
56
|
|
|
$result = base64_decode($data, true); |
57
|
|
|
if (false === $result) { |
58
|
|
|
throw new InvalidArgumentException('invalid base64 string'); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
return $result; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|