-
-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathfile_stream_read.php
More file actions
49 lines (41 loc) · 1.38 KB
/
file_stream_read.php
File metadata and controls
49 lines (41 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
use React\Filesystem\Factory;
use React\Filesystem\Node\FileInterface;
use React\Stream\ReadableStreamInterface;
use React\Stream\ThroughStream;
require 'vendor/autoload.php';
const READ_CHUNK_SIZE = 16; // Use 65536 for everything but this example
function streamFile(FileInterface $file): ReadableStreamInterface
{
$offset = 0;
$stream = new ThroughStream();
$read = function () use (&$read, $stream, &$offset, $file): void {
$file->getContents($offset, READ_CHUNK_SIZE)->then(
function (string $contents) use (&$read, $stream, &$offset, $file): void {
$length = strlen($contents);
if ($length === 0) {
$stream->end('');
return;
}
$offset += $length;
$stream->write($contents);
$read();
},
function (Throwable $throwable) use ($stream) {
$stream->emit('error', $throwable);
$stream->close();
}
);
};
$read();
return $stream;
}
Factory::create()->detect(__FILE__)->then(function (FileInterface $file) {
$stream = streamFile($file);
$stream->on('data', function (string $contents): void {
echo $contents;
});
$stream->on('error', function (Throwable $throwable): void {
echo $throwable;
});
})->done();