Created
April 17, 2018 19:45
-
-
Save hollodotme/fff0d1841fe34a0c989304374363840f to your computer and use it in GitHub Desktop.
Passthrough callback with timed buffer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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