-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathload.php
More file actions
58 lines (51 loc) · 1.43 KB
/
load.php
File metadata and controls
58 lines (51 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
namespace Load;
/**
* function to remove something that was written in CLI by character count
* @param int $count
* @return null
*/
function removeLastCharsByCount(int $count) {
$toRemove = str_repeat(' ', $count);
fwrite(fopen('php://output', 'w'), "$toRemove\r");
}
/**
* function to render frames of an loading animation and evaluate on each tick if the condition resolved itself
* @param array $frames
* @param callable $checkClosure
* @param string $doneText
* @return null
*/
function loop(
array $frames,
callable $checkClosure,
string $doneText
) {
$stopped = false;
$lastMessageLength = 0;
while (!$stopped) {
removeLastCharsByCount($lastMessageLength);
$currentFrame = current($frames);
$closureResult = call_user_func($checkClosure);
if (is_string($closureResult) || is_numeric($closureResult)) {
$outputString = "$currentFrame $closureResult";
$lastMessageLength = strlen($closureResult);
fwrite(fopen('php://output', 'w'), $outputString);
usleep(100000);
next($frames);
if (!current($frames)) {
reset($frames);
}
continue;
}
if (is_bool($closureResult) && $closureResult === true) {
$stopped = true;
removeLastCharsByCount($lastMessageLength + 16);
fwrite(fopen('php://output', 'w'), "$doneText\n");
}
if (is_bool($closureResult) && $closureResult === false) {
removeLastCharsByCount($lastMessageLength + 64);
throw new \Exception('Process failed.');
}
}
}