1
0
mirror of https://github.com/danog/byte-stream.git synced 2024-11-27 04:14:49 +01:00
byte-stream/lib/ZlibOutputStream.php

89 lines
2.3 KiB
PHP
Raw Normal View History

2017-05-08 08:51:52 +02:00
<?php
namespace Amp\ByteStream;
use Amp\Promise;
final class ZlibOutputStream implements OutputStream {
2017-05-08 08:51:52 +02:00
private $destination;
private $encoding;
private $options;
2017-05-08 08:51:52 +02:00
private $resource;
/**
* @param OutputStream $destination
* @param int $encoding
* @param array $options
*
* @throws StreamException
* @throws \Error
*
* @see http://php.net/manual/en/function.deflate-init.php
*/
public function __construct(OutputStream $destination, int $encoding, array $options = []) {
2017-05-08 08:51:52 +02:00
$this->destination = $destination;
$this->encoding = $encoding;
$this->options = $options;
$this->resource = @\deflate_init($encoding, $options);
2017-05-08 08:51:52 +02:00
if ($this->resource === false) {
throw new StreamException("Failed initializing deflate context");
}
}
public function write(string $data): Promise {
if ($this->resource === null) {
throw new ClosedException("The stream has already been closed");
}
$compressed = \deflate_add($this->resource, $data, \ZLIB_SYNC_FLUSH);
if ($compressed === false) {
throw new StreamException("Failed adding data to deflate context");
}
$promise = $this->destination->write($compressed);
$promise->onResolve(function ($error) {
if ($error) {
$this->close();
}
});
return $promise;
}
public function end(string $finalData = ""): Promise {
if ($this->resource === null) {
throw new ClosedException("The stream has already been closed");
}
$compressed = \deflate_add($this->resource, $finalData, \ZLIB_FINISH);
if ($compressed === false) {
throw new StreamException("Failed adding data to deflate context");
}
$promise = $this->destination->write($compressed);
$promise->onResolve(function ($error) {
if ($error) {
$this->close();
}
});
return $promise;
}
2017-05-12 01:08:45 +02:00
protected function close() {
2017-05-08 08:51:52 +02:00
$this->resource = null;
$this->destination = null;
2017-05-08 08:51:52 +02:00
}
public function getEncoding(): int {
return $this->encoding;
}
public function getOptions(): array {
return $this->options;
}
2017-05-08 08:51:52 +02:00
}