phasync
Streams and files / Examples

Streams and files

Examples

Every example of this topic, with its output.

DeadmanException#

Example 1
phasync::run(function () {
    $buffer = new phasync\Util\StringBuffer();
    phasync::go(function () use ($buffer) {
        $switch = $buffer->getDeadmanSwitch();
        $buffer->write('partial');      // and exits without $buffer->end()
    });
    echo $buffer->read(100), "\n";      // partial
    try {
        $buffer->read(100);
    } catch (phasync\DeadmanException $e) {
        echo $e->getMessage(), "\n";    // Writer terminated unexpectedly
    }
});

BufferedStream#

Example 1
$stream = new BufferedStream();

phasync::go(function () use ($stream) {
    $stream->append('A chunk');
    $stream->end();
});

$size = $stream->getSize();   // waits for end(): 7

StringStream#

Example 1
$stream = new StringStream('Hello');
$stream->read(2);        // "He"
$stream->getSize();      // 5

UnbufferedStream#

Example 1
$stream = new UnbufferedStream();

phasync::go(function () use ($stream) {
    foreach (['one', 'two', 'three'] as $chunk) {
        $stream->append($chunk . "\n");
        phasync::sleep(0.1);
    }
    $stream->end();
});

// A server sends this body to the client, reading it from another coroutine
$response = $response->withBody($stream);

UploadedFile#

Example 1
$file = new UploadedFile($_FILES['avatar']['tmp_name'], $_FILES['avatar']['name'], $_FILES['avatar']['type'], $_FILES['avatar']['size'], $_FILES['avatar']['error']);
if (UPLOAD_ERR_OK === $file->getError()) {
    $file->moveTo('/var/uploads/avatar.png');
}

StringBuffer#

Example 1
phasync::run(function () {
    $buffer = new phasync\Util\StringBuffer();

    phasync::go(function () use ($buffer) {
        $buffer->write("he");
        phasync::sleep(0.01);
        $buffer->write("llo\n");
        $buffer->end();
    });

    var_dump($buffer->readFixed(5));   // string(5) "hello", after both writes
    var_dump($buffer->read(10));       // string(1) "\n"
    var_dump($buffer->read(10));       // string(0) "": the buffer has ended
});

MultipartStream#

Example 1Upload a file with form fields
use phasync\HttpClient\HttpClient;
use phasync\HttpClient\MultipartStream;

$base = require __DIR__ . '/../server.php';

$file = tmpfile();
fwrite($file, "id,name\n1,Ada\n");
rewind($file);

$body = new MultipartStream([
    'title'  => 'Customers',
    'tags'   => ['import', 'csv'],
    'upload' => $file,
], 'example-boundary');
echo $body->getContentType(), "\n";

$echo = json_decode((string) (new HttpClient())->post("$base/echo", $body)->getBody(), true);
echo json_encode($echo['form']), "\n";
echo 'file of ', $echo['files']['upload']['size'], " bytes\n";
Output
multipart/form-data; boundary=example-boundary
{"title":"Customers","tags":["import","csv"]}
file of 14 bytes

MultipartStream#

Example 1
$body = new MultipartStream([
    'title'      => 'My upload',
    'tags'       => ['a', 'b'],
    'attachment' => fopen('/path/to/file.txt', 'r'),
]);
$response = $client->post('https://example.com/upload', $body);

MultipartStream::__construct#

Example 1
$body = new MultipartStream(['name' => 'Frode', 'files' => [\fopen('a.txt', 'r'), \fopen('b.txt', 'r')]]);

MultipartStream::getContentType#

Example 1
$body = new MultipartStream(['a' => '1'], 'my-boundary');
echo $body->getContentType(); // multipart/form-data; boundary=my-boundary

MultipartStreamInterface#

Example 1The Content-Type comes with the body
use phasync\HttpClient\HttpClient;
use phasync\HttpClient\MultipartStream;
use phasync\HttpClient\MultipartStreamInterface;
use phasync\Psr\Request;

$base = require __DIR__ . '/../server.php';

$body = new MultipartStream(['comment' => 'looks good'], 'b0undary');
var_dump($body instanceof MultipartStreamInterface);

// sendRequest() sets Content-Type, with the boundary, from the body
$request  = Request::create('POST', "$base/echo")->withBody($body);
$echo     = json_decode((string) (new HttpClient())->sendRequest($request)->getBody(), true);
echo $echo['headers']['content-type'], "\n";
echo json_encode($echo['form']), "\n";
Output
bool(true)
multipart/form-data; boundary=b0undary
{"comment":"looks good"}

MultipartStreamInterface#

Example 1
$body = new MultipartStream(['title' => 'Report', 'file' => \fopen('report.pdf', 'r')]);
$client->post('https://example.com/upload', $body); // Content-Type: $body->getContentType()

MultipartStreamInterface::getContentType#

Example 1
echo $body->getContentType(); // multipart/form-data; boundary=phasync4f2a...