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

55 lines
1.1 KiB
PHP
Raw Normal View History

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);
}
}