Passed
Branch master (911f86)
by Timm
01:57
created

Progress   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 33
c 3
b 0
f 0
dl 0
loc 73
ccs 0
cts 43
cp 0
rs 10
wmc 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getStatusbar() 0 10 2
A getRate() 0 3 2
A showStatus() 0 47 4
A getFactor() 0 3 2
1
<?php
2
3
4
namespace Stefaminator\Cli;
5
6
7
class Progress {
8
9
10
    public static function showStatus(int $done, int $total, int $size = 30): void {
11
12
        static $start_time = NULL;
13
14
        // if we go over our bound, just ignore it
15
        if ($done > $total) {
16
            return;
17
        }
18
19
        if (empty($start_time)) {
20
            $start_time = time();
21
        }
22
23
        $now = time();
24
25
        $factor = self::getFactor($total, $done);
26
27
        $status_bar_pb = self::getStatusbar($factor, $size);
28
29
        $status_bar = "\r";
30
        $status_bar .= Color::getColoredString($status_bar_pb, Color::FOREGROUND_COLOR_GREEN, Color::BACKGROUND_COLOR_LIGHT_GRAY);
31
32
        $disp = number_format($factor * 100);
33
34
        $status_bar_percent = str_pad("$disp%", 5, ' ', STR_PAD_LEFT);
35
        $status_bar .= Color::getColoredString($status_bar_percent, Color::FOREGROUND_COLOR_GREEN);
36
37
        $status_bar_done = " $done/$total";
38
39
        $status_bar .= Color::getColoredString($status_bar_done, Color::FOREGROUND_COLOR_YELLOW);
40
41
        $rate = self::getRate($now - $start_time, $done);
42
        $left = $total - $done;
43
        $eta = round($rate * $left, 2);
44
45
        $elapsed = $now - $start_time;
46
47
        $status_bar .= ' remaining: ' . number_format($eta) . ' sec. elapsed: ' . number_format($elapsed) . ' sec.';
48
49
        echo "$status_bar ";
50
51
        flush();
52
53
        // when done, send a newline
54
        if ($done === $total) {
55
            echo "\n";
56
            $start_time = NULL;
57
        }
58
    }
59
60
    private static function getStatusbar(float $factor, int $size): string {
61
62
        $bar = (int)round($factor * $size);
63
64
        $status_bar_pb = str_repeat('█', $bar);
65
        if ($bar < $size) {
66
            $status_bar_pb .= str_repeat(' ', $size - $bar);
67
        }
68
69
        return $status_bar_pb;
70
    }
71
72
    private static function getFactor(int $total, int $done): float {
73
74
        return (float)(($total === 0) ? 1 : ($done / $total));
75
    }
76
77
    private static function getRate(int $seconds, int $done): float {
78
79
        return (float)(($done === 0) ? 0 : ($seconds / $done));
80
    }
81
}