<?php declare(strict_types=1);
namespace Inhere\Console\Component\Progress;
use Generator;
use Inhere\Console\Component\NotifyMessage;
use Inhere\Console\Console;
use Toolkit\Cli\Cli;
use function array_merge;
use function ceil;
class SimpleBar extends NotifyMessage
{
public static function gen(int $total, array $opts = []): Generator
{
$current = 0;
$finished = false;
$tplPrefix = Cli::isSupportColor() ? "\x0D\x1B[2K" : "\x0D\r";
$opts = array_merge([
'doneChar' => '=',
'waitChar' => ' ',
'signChar' => '>',
'msg' => '',
'doneMsg' => '',
], $opts);
$msg = Console::style()->render($opts['msg']);
$doneMsg = Console::style()->render($opts['doneMsg']);
$waitChar = $opts['waitChar'];
while (true) {
if ($finished) {
break;
}
$step = yield;
if ((int)$step <= 0) {
$step = 1;
}
$current += $step;
$percent = ceil(($current / $total) * 100);
if ($percent >= 100) {
$msg = $doneMsg ?: $msg;
$percent = 100;
$finished = true;
}
printf(
"{$tplPrefix}[%'{$waitChar}-100s] %' 3d%% %s",
str_repeat($opts['doneChar'], $percent) . ($finished ? '' : $opts['signChar']),
$percent,
$msg
)
if ($finished) {
echo "\n";
break;
}
}
yield false;
}
}