Last active
May 12, 2021 12:33
-
-
Save dasl-/eca8cca4228779f89d3ea16afaedfdbe to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#!/usr/bin/env php | |
<?php | |
function helpMessage($exit = 0) { | |
echo <<<EOT | |
Delay output by specified number of seconds. | |
-t <float> duration in seconds | |
EOT; | |
exit($exit); | |
} | |
$args = getopt("ht:", []); | |
if (isset($args["h"])) { | |
helpMessage(); | |
} | |
if (!isset($args['t'])) { | |
helpMessage(1); | |
} | |
$delay_s = (float) $args['t']; | |
ini_set("memory_limit", "-1"); | |
$start = microtime(true); | |
$buffer = ''; | |
$is_delay_over = false; | |
while (($bytes = fread(STDIN, 4096)) || !$is_delay_over) { | |
$elapsed = microtime(true) - $start; | |
if ($elapsed > $delay_s) { | |
if ($is_delay_over && $bytes !== false) { | |
echo $bytes; | |
} else { | |
$is_delay_over = true; | |
// not sure if this loop is necessary or if I can just `echo $buffer;` ? | |
$buffer_piece_index = 0; | |
while ($buffer_piece = substr($buffer, $buffer_piece_index, 4096)) { | |
$buffer_piece_index += 4096; | |
echo $buffer_piece; | |
} | |
if ($bytes !== false) { | |
echo $bytes; | |
} | |
} | |
} else if ($bytes !== false) { | |
$buffer .= $bytes; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment