1
0
mirror of https://github.com/danog/amp.git synced 2024-12-04 02:17:54 +01:00
amp/lib/StreamSource.php

89 lines
2.1 KiB
PHP
Raw Normal View History

2020-05-13 17:15:21 +02:00
<?php
namespace Amp;
/**
2020-05-28 19:59:55 +02:00
* StreamSource is a container for a Stream that can emit values using the emit() method and completed using the
2020-05-13 17:15:21 +02:00
* complete() and fail() methods. The contained Stream may be accessed using the stream() method. This object should
2020-05-28 19:59:55 +02:00
* not be returned as part of a public API, but used internally to create and emit values to a Stream.
2020-05-13 17:15:21 +02:00
*
* @template TValue
*/
final class StreamSource
{
2020-05-28 19:59:55 +02:00
/** @var Internal\EmitSource<TValue, null> Has public emit, complete, and fail methods. */
private $source;
2020-05-13 17:15:21 +02:00
public function __construct()
{
2020-05-28 19:59:55 +02:00
$this->source = new Internal\EmitSource;
2020-05-13 17:15:21 +02:00
}
/**
* Returns a Stream that can be given to an API consumer. This method may be called only once!
*
* @return Stream
*
* @psalm-return Stream<TValue>
*
* @throws \Error If this method is called more than once.
2020-05-13 17:15:21 +02:00
*/
public function stream(): Stream
{
return $this->source->stream();
2020-05-13 17:15:21 +02:00
}
/**
2020-05-28 19:59:55 +02:00
* Emits a value to the stream.
2020-05-13 17:15:21 +02:00
*
* @param mixed $value
*
* @psalm-param TValue $value
*
2020-05-28 19:59:55 +02:00
* @return Promise<null> Resolves with null when the emitted value has been consumed or fails with
2020-05-13 17:15:21 +02:00
* {@see DisposedException} if the stream has been destroyed.
*/
2020-05-28 19:59:55 +02:00
public function emit($value): Promise
2020-05-13 17:15:21 +02:00
{
2020-05-28 19:59:55 +02:00
return $this->source->emit($value);
2020-05-13 17:15:21 +02:00
}
/**
* @return bool True if the stream has been completed or failed.
*/
public function isComplete(): bool
{
return $this->source->isComplete();
}
2020-07-17 18:22:13 +02:00
/**
* @return bool True if the stream has been disposed.
*/
public function isDisposed(): bool
{
return $this->source->isDisposed();
}
2020-05-13 17:15:21 +02:00
/**
* Completes the stream.
*
* @return void
*/
public function complete()
{
$this->source->complete();
2020-05-13 17:15:21 +02:00
}
/**
* Fails the stream with the given reason.
*
* @param \Throwable $reason
*
* @return void
*/
public function fail(\Throwable $reason)
{
$this->source->fail($reason);
2020-05-13 17:15:21 +02:00
}
}