PHP code example of wp-php-toolkit / bytestream
1. Go to this page and download the library: Download wp-php-toolkit/bytestream library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
wp-php-toolkit / bytestream example snippets
WordPress\ByteStream\ReadStream\FileReadStream;
$path = tempnam( sys_get_temp_dir(), 'demo' );
file_put_contents( $path, str_repeat( "log line\n", 200 ) );
$reader = FileReadStream::from_path( $path );
$total = 0;
while ( ! $reader->reached_end_of_data() ) {
$n = $reader->pull( 256 );
if ( 0 === $n ) break;
$total += strlen( $reader->consume( $n ) );
}
$reader->close_reading();
echo "Read {$total} bytes in 256-byte chunks.\n";
WordPress\ByteStream\MemoryPipe;
$pipe = new MemoryPipe();
$pipe->append_bytes( "first chunk\n" );
$pipe->append_bytes( "second chunk\n" );
$pipe->append_bytes( "third chunk\n" );
$pipe->close_writing();
while ( ! $pipe->reached_end_of_data() ) {
$n = $pipe->pull( 1024 );
if ( 0 === $n ) break;
echo "got: " . $pipe->consume( $n );
}
WordPress\ByteStream\MemoryPipe;
use WordPress\ByteStream\ReadStream\DeflateReadStream;
use WordPress\ByteStream\ReadStream\InflateReadStream;
$original = str_repeat( "the quick brown fox. ", 50 );
$src = new MemoryPipe( $original );
$src->close_writing();
$deflated = new DeflateReadStream( $src, ZLIB_ENCODING_DEFLATE );
$compressed = $deflated->consume_all();
$src2 = new MemoryPipe( $compressed );
$src2->close_writing();
$inflated = new InflateReadStream( $src2, ZLIB_ENCODING_DEFLATE );
$round = $inflated->consume_all();
printf( "original : %d bytes\n", strlen( $original ) );
printf( "deflated : %d bytes (%.1f%%)\n", strlen( $compressed ), 100 * strlen( $compressed ) / strlen( $original ) );
printf( "round-trip: %s\n", $round === $original ? 'OK' : 'BROKEN' );
WordPress\ByteStream\MemoryPipe;
$pipe = new MemoryPipe();
$pipe->append_bytes( "alpha\nbravo\ncharl" );
$pipe->append_bytes( "ie\ndelta\necho\n" );
$pipe->close_writing();
$tail = '';
$count = 0;
while ( ! $pipe->reached_end_of_data() ) {
$n = $pipe->pull( 8 );
if ( 0 === $n ) break;
$buf = $tail . $pipe->consume( $n );
$lines = explode( "\n", $buf );
$tail = array_pop( $lines );
foreach ( $lines as $line ) {
printf( "[%d] %s\n", ++$count, $line );
}
}
if ( '' !== $tail ) {
printf( "[%d] %s\n", ++$count, $tail );
}
WordPress\ByteStream\MemoryPipe;
use WordPress\ByteStream\ReadStream\LimitedByteReadStream;
$source = new MemoryPipe( "HEADER:42|BODY:hello there|FOOTER:done" );
$source->close_writing();
$source->pull( 10 );
$source->consume( 10 );
$body = new LimitedByteReadStream( $source, 16 );
echo "body sees: " . $body->consume_all() . "\n";
echo "remaining in source: " . $source->consume_all() . "\n";
[1] alpha
[2] bravo
[3] charlie
[4] delta
[5] echo