Passed
Push — master ( 74eb15...800a06 )
by Timm
01:55
created

Progress::getStatusbar()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 8
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 13
rs 10
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)floor($factor * $size);
63
64
        $status_bar_pb = str_repeat('█', $bar);
65
        if ($bar < $size) {
66
            $status_bar_pb .= '█';
67
            $status_bar_pb .= str_repeat(' ', $size - $bar);
68
        } else {
69
            $status_bar_pb .= '█';
70
        }
71
72
        return $status_bar_pb;
73
    }
74
75
    private static function getFactor(int $total, int $done): float {
76
77
        return (double)(($total === 0) ? 1: ($done / $total));
78
    }
79
80
    private static function getRate(int $seconds, int $done): float {
81
82
        return (double)(($done === 0) ? 0 : ($seconds / $done));
83
    }
84
}