1
0
mirror of https://github.com/danog/byte-stream.git synced 2024-11-26 20:04:51 +01:00
byte-stream/lib/GzipInputStream.php

58 lines
1.4 KiB
PHP
Raw Normal View History

2017-05-05 22:39:39 +02:00
<?php
namespace Amp\ByteStream;
use Amp\Promise;
use function Amp\call;
class GzipInputStream implements InputStream {
private $source;
private $resource;
public function __construct(InputStream $source) {
$this->source = $source;
$this->resource = \inflate_init(\ZLIB_ENCODING_GZIP);
if ($this->resource === false) {
throw new StreamException("Failed initializing deflate context");
}
}
public function read(): Promise {
return call(function () {
if ($this->resource === null) {
return null;
}
2017-05-05 22:39:39 +02:00
$data = yield $this->source->read();
if ($data === null) {
$decompressed = \inflate_add($this->resource, "", \ZLIB_FINISH);
2017-05-05 22:39:39 +02:00
if ($decompressed === false) {
throw new StreamException("Failed adding data to deflate context");
}
$this->close();
2017-05-05 22:39:39 +02:00
return $decompressed;
}
$decompressed = \inflate_add($this->resource, $data, \ZLIB_SYNC_FLUSH);
if ($decompressed === false) {
throw new StreamException("Failed adding data to deflate context");
}
return $decompressed;
});
}
public function close() {
$this->resource = null;
2017-05-05 22:39:39 +02:00
$this->source->close();
$this->source = null;
2017-05-05 22:39:39 +02:00
}
2017-05-07 22:14:45 +02:00
}