1
0
mirror of https://github.com/danog/byte-stream.git synced 2024-11-30 04:19:23 +01:00
byte-stream/lib/ZlibInputStream.php

85 lines
2.1 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;
final class ZlibInputStream implements InputStream {
2017-05-05 22:39:39 +02:00
private $source;
private $encoding;
private $options;
2017-05-05 22:39:39 +02:00
private $resource;
/**
* ZlibInputStream constructor.
*
* @param InputStream $source
* @param int $encoding
* @param array $options
*
* @throws StreamException
* @throws \Error
*
* @see http://php.net/manual/en/function.inflate-init.php
*/
public function __construct(InputStream $source, int $encoding, array $options = []) {
2017-05-05 22:39:39 +02:00
$this->source = $source;
$this->encoding = $encoding;
$this->options = $options;
$this->resource = @\inflate_init($encoding, $options);
2017-05-05 22:39:39 +02:00
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();
// Needs a double guard, as stream might have been closed while reading
if ($this->resource === null) {
return null;
}
2017-05-05 22:39:39 +02:00
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;
});
}
2017-05-12 01:08:45 +02:00
protected function close() {
$this->resource = null;
$this->source = null;
2017-05-05 22:39:39 +02:00
}
public function getEncoding(): int {
return $this->encoding;
}
public function getOptions(): array {
return $this->options;
}
2017-05-07 22:14:45 +02:00
}