|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Mfonte\Base62x\Compression\Gzip; |
|
4
|
|
|
|
|
5
|
|
|
use Mfonte\Base62x\Exception\CompressionException; |
|
6
|
|
|
|
|
7
|
|
|
class GzipCompression |
|
8
|
|
|
{ |
|
9
|
|
|
public static function encode($data, $encoding = null) |
|
10
|
|
|
{ |
|
11
|
|
|
if (!\function_exists('gzencode')) { |
|
12
|
|
|
throw new CompressionException('gzip', 'Cannot use Gzip as compression algorithm: the current PHP installation does not support this module.'); |
|
13
|
|
|
} |
|
14
|
|
|
|
|
15
|
|
|
$encoded = false; |
|
16
|
|
|
switch ($encoding) { |
|
17
|
|
|
case 'zlib': |
|
18
|
|
|
$encoded = @gzcompress($data, 9); |
|
19
|
|
|
break; |
|
20
|
|
|
case 'deflate': |
|
21
|
|
|
$encoded = @gzdeflate($data, 9); |
|
22
|
|
|
break; |
|
23
|
|
|
case 'gzip': |
|
24
|
|
|
$encoded = @gzencode($data, 9); |
|
25
|
|
|
break; |
|
26
|
|
|
default: |
|
27
|
|
|
$encoded = @gzencode($data, 9); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
if ($encoded === false) { |
|
31
|
|
|
throw new CompressionException('gzip', 'The gz compression function returned a false state while compressing the input data.'); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
// avoid data errors: perform a base64_encode prior of returning |
|
35
|
|
|
$encoded = base64_encode($encoded); |
|
36
|
|
|
|
|
37
|
|
|
return $encoded; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
public static function decode($data, $encoding = null) |
|
41
|
|
|
{ |
|
42
|
|
|
if (!\function_exists('gzdecode')) { |
|
43
|
|
|
throw new CompressionException('gzip', 'Cannot use Gzip as compression algorithm: the current PHP installation does not support this module.'); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
// the data comes encoded in base64: see above |
|
47
|
|
|
$data = base64_decode($data, true); |
|
48
|
|
|
|
|
49
|
|
|
$fn = 'gzdecode'; |
|
50
|
|
|
$decoded = false; |
|
51
|
|
|
switch ($encoding) { |
|
52
|
|
|
case 'zlib': |
|
53
|
|
|
$fn = 'gzuncompress'; |
|
54
|
|
|
$decoded = @gzuncompress($data); |
|
55
|
|
|
break; |
|
56
|
|
|
case 'deflate': |
|
57
|
|
|
$fn = 'gzinflate'; |
|
58
|
|
|
$decoded = @gzinflate($data); |
|
59
|
|
|
break; |
|
60
|
|
|
case 'gzip': |
|
61
|
|
|
$decoded = @gzdecode($data); |
|
62
|
|
|
break; |
|
63
|
|
|
default: |
|
64
|
|
|
$decoded = @gzdecode($data); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
if ($decoded === false) { |
|
68
|
|
|
throw new CompressionException('gzip', "The {$fn}() function returned a false state while uncompressing the input data."); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
return $decoded; |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|