Repository navigation
Expand file tree
/
Copy pathDeflateWriter.php
More file actions
96 lines (83 loc) · 2.56 KB
/
Copy pathDeflateWriter.php
File metadata and controls
96 lines (83 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?php
namespace samdark\sitemap;
use RuntimeException;
/**
* Flushes buffer into file with incremental deflating data.
*/
class DeflateWriter implements WriterInterface
{
/**
* @var ?resource For target file.
*/
private $file = null;
/**
* @var resource|\DeflateContext|null For writable incremental deflate context.
* @phpstan-var \DeflateContext|null For writable incremental deflate context.
*/
private $deflateContext = null;
/**
* @param string $filename Target file.
*/
public function __construct(string $filename)
{
if (!function_exists('deflate_init')) {
// @codeCoverageIgnoreStart
throw new RuntimeException('ext-zlib is not available.');
// @codeCoverageIgnoreEnd
}
if (is_dir($filename)) {
throw new RuntimeException("Unable to open \"$filename\".");
}
$file = fopen($filename, 'ab');
if ($file === false) {
// @codeCoverageIgnoreStart
throw new RuntimeException("Unable to open \"$filename\".");
// @codeCoverageIgnoreEnd
}
$this->file = $file;
$deflateContext = deflate_init(ZLIB_ENCODING_GZIP);
if ($deflateContext === false) {
// @codeCoverageIgnoreStart
throw new RuntimeException("Unable to open deflate context.");
// @codeCoverageIgnoreEnd
}
$this->deflateContext = $deflateContext;
}
/**
* Deflate data in a deflate context and write it to the target file.
*
* @param string $data Data to write.
* @param int $flushMode Zlib flush mode to use for writing.
*/
private function write(string $data, int $flushMode): void
{
if ($this->file === null || $this->deflateContext === null) {
return;
}
$compressedChunk = deflate_add($this->deflateContext, $data, $flushMode);
if ($compressedChunk === false) {
// @codeCoverageIgnoreStart
throw new RuntimeException('Failed to add deflate.');
// @codeCoverageIgnoreEnd
}
fwrite($this->file, $compressedChunk);
}
/**
* Store data in a deflate stream.
*
* @param string $data Data to write.
*/
public function append(string $data): void
{
$this->write($data, ZLIB_NO_FLUSH);
}
/**
* Make sure all data was written.
*/
public function finish(): void
{
$this->write('', ZLIB_FINISH);
$this->file = null;
$this->deflateContext = null;
}
}