1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace Sop\JWX\JWE\CompressionAlgorithm; |
6
|
|
|
|
7
|
|
|
use Sop\JWX\JWA\JWA; |
8
|
|
|
use Sop\JWX\JWE\CompressionAlgorithm; |
9
|
|
|
use Sop\JWX\JWT\Parameter\CompressionAlgorithmParameter; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Implements DEFLATE compression algorithm. |
13
|
|
|
* |
14
|
|
|
* @see https://tools.ietf.org/html/rfc7516#section-4.1.3 |
15
|
|
|
* @see https://tools.ietf.org/html/rfc1951 |
16
|
|
|
*/ |
17
|
|
|
class DeflateAlgorithm implements CompressionAlgorithm |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* Compression level. |
21
|
|
|
* |
22
|
|
|
* @var int |
23
|
|
|
*/ |
24
|
|
|
protected $_compressionLevel; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Constructor. |
28
|
|
|
* |
29
|
|
|
* @param int $level Compression level 0..9 |
30
|
|
|
*/ |
31
|
10 |
|
public function __construct(int $level = -1) |
32
|
|
|
{ |
33
|
10 |
|
if ($level < -1 || $level > 9) { |
34
|
1 |
|
throw new \DomainException('Compression level must be -1..9.'); |
35
|
|
|
} |
36
|
9 |
|
$this->_compressionLevel = $level; |
37
|
9 |
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* {@inheritdoc} |
41
|
|
|
* |
42
|
|
|
* @throws \RuntimeException |
43
|
|
|
*/ |
44
|
6 |
|
public function compress(string $data): string |
45
|
|
|
{ |
46
|
6 |
|
$ret = @gzdeflate($data, $this->_compressionLevel); |
47
|
6 |
|
if (false === $ret) { |
48
|
1 |
|
$err = error_get_last(); |
49
|
1 |
|
$msg = isset($err) && __FILE__ === $err['file'] ? $err['message'] : null; |
50
|
1 |
|
throw new \RuntimeException($msg ?? 'gzdeflate() failed.'); |
51
|
|
|
} |
52
|
5 |
|
return $ret; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* {@inheritdoc} |
57
|
|
|
* |
58
|
|
|
* @throws \RuntimeException |
59
|
|
|
*/ |
60
|
4 |
|
public function decompress(string $data): string |
61
|
|
|
{ |
62
|
4 |
|
$ret = @gzinflate($data); |
63
|
4 |
|
if (false === $ret) { |
64
|
1 |
|
$err = error_get_last(); |
65
|
1 |
|
$msg = isset($err) && __FILE__ === $err['file'] ? $err['message'] : null; |
66
|
1 |
|
throw new \RuntimeException($msg ?? 'gzinflate() failed.'); |
67
|
|
|
} |
68
|
3 |
|
return $ret; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* {@inheritdoc} |
73
|
|
|
*/ |
74
|
5 |
|
public function compressionParamValue(): string |
75
|
|
|
{ |
76
|
5 |
|
return JWA::ALGO_DEFLATE; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
/** |
80
|
|
|
* {@inheritdoc} |
81
|
|
|
*/ |
82
|
3 |
|
public function headerParameters(): array |
83
|
|
|
{ |
84
|
3 |
|
return [CompressionAlgorithmParameter::fromAlgorithm($this)]; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|