| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Jose\Component\Encryption\Compression; |
| 6 |
|
| 7 |
use InvalidArgumentException; |
| 8 |
use Throwable; |
| 9 |
use function is_string; |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
final class Deflate implements CompressionMethod |
| 15 |
{ |
| 16 |
private int $compressionLevel = -1; |
| 17 |
|
| 18 |
public function __construct(int $compressionLevel = -1) |
| 19 |
{ |
| 20 |
if ($compressionLevel < -1 || $compressionLevel > 9) { |
| 21 |
throw new InvalidArgumentException( |
| 22 |
'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.' |
| 23 |
); |
| 24 |
} |
| 25 |
$this->compressionLevel = $compressionLevel; |
| 26 |
} |
| 27 |
|
| 28 |
public function name(): string |
| 29 |
{ |
| 30 |
return 'DEF'; |
| 31 |
} |
| 32 |
|
| 33 |
public function compress(string $data): string |
| 34 |
{ |
| 35 |
try { |
| 36 |
$bin = gzdeflate($data, $this->getCompressionLevel()); |
| 37 |
if (! is_string($bin)) { |
| 38 |
throw new InvalidArgumentException('Unable to encode the data'); |
| 39 |
} |
| 40 |
|
| 41 |
return $bin; |
| 42 |
} catch (Throwable $throwable) { |
| 43 |
throw new InvalidArgumentException('Unable to compress data.', $throwable->getCode(), $throwable); |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
public function uncompress(string $data): string |
| 48 |
{ |
| 49 |
try { |
| 50 |
$bin = gzinflate($data); |
| 51 |
if (! is_string($bin)) { |
| 52 |
throw new InvalidArgumentException('Unable to encode the data'); |
| 53 |
} |
| 54 |
|
| 55 |
return $bin; |
| 56 |
} catch (Throwable $throwable) { |
| 57 |
throw new InvalidArgumentException('Unable to uncompress data.', $throwable->getCode(), $throwable); |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
private function getCompressionLevel(): int |
| 62 |
{ |
| 63 |
return $this->compressionLevel; |
| 64 |
} |
| 65 |
} |