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 () {
|
2017-05-08 09:30:11 +02:00
|
|
|
if ($this->resource === null) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2017-05-05 22:39:39 +02:00
|
|
|
$data = yield $this->source->read();
|
|
|
|
|
|
|
|
if ($data === null) {
|
2017-05-07 11:14:41 +02:00
|
|
|
$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");
|
|
|
|
}
|
|
|
|
|
2017-05-08 09:30:11 +02:00
|
|
|
$this->close();
|
2017-05-07 11:14:41 +02:00
|
|
|
|
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() {
|
2017-05-07 11:14:41 +02:00
|
|
|
$this->resource = null;
|
|
|
|
|
2017-05-05 22:39:39 +02:00
|
|
|
$this->source->close();
|
2017-05-08 09:30:11 +02:00
|
|
|
$this->source = null;
|
2017-05-05 22:39:39 +02:00
|
|
|
}
|
2017-05-07 22:14:45 +02:00
|
|
|
}
|