Skip to content

Instantly share code, notes, and snippets.

@dasl-
Last active May 12, 2021 12:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dasl-/eca8cca4228779f89d3ea16afaedfdbe to your computer and use it in GitHub Desktop.
Save dasl-/eca8cca4228779f89d3ea16afaedfdbe to your computer and use it in GitHub Desktop.
#!/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