2017-10-17 21:11:35 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Amp\ByteStream;
|
|
|
|
|
|
|
|
use Amp\Deferred;
|
|
|
|
use Amp\Promise;
|
|
|
|
use Amp\Success;
|
|
|
|
|
2018-09-21 22:45:13 +02:00
|
|
|
class OutputBuffer implements OutputStream, Promise
|
|
|
|
{
|
2017-10-17 21:11:35 +02:00
|
|
|
/** @var \Amp\Deferred|null */
|
|
|
|
private $deferred;
|
|
|
|
|
|
|
|
/** @var string */
|
|
|
|
private $contents;
|
|
|
|
|
|
|
|
private $closed = false;
|
|
|
|
|
2018-09-21 22:45:13 +02:00
|
|
|
public function __construct()
|
|
|
|
{
|
2017-10-17 21:11:35 +02:00
|
|
|
$this->deferred = new Deferred;
|
|
|
|
}
|
|
|
|
|
2018-09-21 22:45:13 +02:00
|
|
|
public function write(string $data): Promise
|
|
|
|
{
|
2017-10-17 21:11:35 +02:00
|
|
|
if ($this->closed) {
|
|
|
|
throw new ClosedException("The stream has already been closed.");
|
|
|
|
}
|
|
|
|
|
|
|
|
$this->contents .= $data;
|
|
|
|
|
|
|
|
return new Success(\strlen($data));
|
|
|
|
}
|
|
|
|
|
2018-09-21 22:45:13 +02:00
|
|
|
public function end(string $finalData = ""): Promise
|
|
|
|
{
|
2017-10-17 21:11:35 +02:00
|
|
|
if ($this->closed) {
|
|
|
|
throw new ClosedException("The stream has already been closed.");
|
|
|
|
}
|
|
|
|
|
|
|
|
$this->contents .= $finalData;
|
|
|
|
$this->closed = true;
|
|
|
|
|
|
|
|
$this->deferred->resolve($this->contents);
|
|
|
|
$this->contents = "";
|
|
|
|
|
|
|
|
return new Success(\strlen($finalData));
|
|
|
|
}
|
|
|
|
|
2018-09-21 22:45:13 +02:00
|
|
|
public function onResolve(callable $onResolved)
|
|
|
|
{
|
2017-10-17 21:11:35 +02:00
|
|
|
$this->deferred->promise()->onResolve($onResolved);
|
|
|
|
}
|
|
|
|
}
|