Skip to content

Instantly share code, notes, and snippets.

@hollodotme
Created April 17, 2018 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hollodotme/fff0d1841fe34a0c989304374363840f to your computer and use it in GitHub Desktop.
Save hollodotme/fff0d1841fe34a0c989304374363840f to your computer and use it in GitHub Desktop.
Passthrough callback with timed buffer
<?php declare(strict_types=1);
final class TimedBuffer
{
private $buffer = '';
private $intervalMs;
private $startTime;
public function __construct( int $intervalMs )
{
$this->startTime = microtime( true );
$this->intervalMs = $intervalMs;
}
public function write( string $content ) : void
{
$this->buffer .= $content;
}
public function flush() : void
{
$compareTime = microtime( true ) - $this->intervalMs;
if ( $compareTime < $this->startTime )
{
return;
}
# Wherever you want to flush the buffer to goes here
echo $this->buffer;
flush();
$this->buffer = '';
$this->startTime = $compareTime;
}
}
$timedBuffer = new TimedBuffer( 500 );
$passThroughCallback = function ( string $buffer ) use ( $timedBuffer )
{
$timedBuffer->write( $buffer );
$timedBuffer->flush();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment