1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* The MIT License (MIT) |
7
|
|
|
* |
8
|
|
|
* Copyright (c) 2014-2019 Spomky-Labs |
9
|
|
|
* |
10
|
|
|
* This software may be modified and distributed under the terms |
11
|
|
|
* of the MIT license. See the LICENSE file for details. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Jose\Component\Encryption\Compression; |
15
|
|
|
|
16
|
|
|
use InvalidArgumentException; |
17
|
|
|
use Throwable; |
18
|
|
|
|
19
|
|
|
final class Deflate implements CompressionMethod |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @var int |
23
|
|
|
*/ |
24
|
|
|
private $compressionLevel = -1; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Deflate constructor. |
28
|
|
|
* |
29
|
|
|
* @throws InvalidArgumentException if the compression level is invalid |
30
|
|
|
*/ |
31
|
|
|
public function __construct(int $compressionLevel = -1) |
32
|
|
|
{ |
33
|
|
|
if ($compressionLevel < -1 || $compressionLevel > 9) { |
34
|
|
|
throw new InvalidArgumentException('The compression level can be given as 0 for no compression up to 9 for maximum compression. If -1 given, the default compression level will be the default compression level of the zlib library.'); |
35
|
|
|
} |
36
|
|
|
$this->compressionLevel = $compressionLevel; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function name(): string |
40
|
|
|
{ |
41
|
|
|
return 'DEF'; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @throws InvalidArgumentException if the compression failed |
46
|
|
|
*/ |
47
|
|
|
public function compress(string $data): string |
48
|
|
|
{ |
49
|
|
|
try { |
50
|
|
|
return gzdeflate($data, $this->getCompressionLevel()); |
51
|
|
|
} catch (Throwable $throwable) { |
52
|
|
|
throw new InvalidArgumentException('Unable to compress data.', $throwable->getCode(), $throwable); |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @throws InvalidArgumentException if the decompression failed |
58
|
|
|
*/ |
59
|
|
|
public function uncompress(string $data): string |
60
|
|
|
{ |
61
|
|
|
try { |
62
|
|
|
return gzinflate($data); |
63
|
|
|
} catch (Throwable $throwable) { |
64
|
|
|
throw new InvalidArgumentException('Unable to uncompress data.', $throwable->getCode(), $throwable); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
private function getCompressionLevel(): int |
69
|
|
|
{ |
70
|
|
|
return $this->compressionLevel; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|