Created
January 30, 2018 13:13
-
-
Save golonix/050e3db15c3a527772cb34e86dee6a6c to your computer and use it in GitHub Desktop.
Artisan command with customized progress bar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Console\Commands; | |
use Illuminate\Console\Command; | |
use Symfony\Component\Console\Helper\Helper; | |
use Symfony\Component\Console\Helper\ProgressBar; | |
class AdvancedAwesomeCommand extends Command | |
{ | |
/** | |
* @var string | |
*/ | |
protected $signature = 'awesome'; | |
/** | |
* @var string | |
*/ | |
protected $description = 'Run awesome command'; | |
/** | |
* @return void | |
*/ | |
public function handle() | |
{ | |
$this->setElapsedPlaceholder(); | |
$this->comment('Doing something awesome ...'); | |
$bar = $this->createProgressBar(); | |
$bar->start(10); | |
for ($i = 0; $i < 10; $i++) { | |
$bar->advance(); | |
usleep(700000); | |
} | |
$bar->finish(); | |
$bar->clear(); | |
$this->clearOutput(); | |
$this->info("Did something awesome \xE2\x9C\x93"); | |
} | |
/** | |
* Re-define 'elapsed' placeholder format | |
* | |
* Add background for the elapsed time, changing depending on the time lapse. | |
* | |
* @return void | |
*/ | |
protected function setElapsedPlaceholder() | |
{ | |
ProgressBar::setPlaceholderFormatterDefinition('elapsed', function (ProgressBar $bar) { | |
$elapsed = time() - $bar->getStartTime(); | |
$colors = $elapsed < 5 ? '42;37' : '41;37'; | |
return sprintf("\033[%sm %s \033[0m", $colors, Helper::formatTime($elapsed)); | |
}); | |
} | |
/** | |
* Create progress bar with custom bar characters | |
* | |
* @return \Symfony\Component\Console\Helper\ProgressBar | |
*/ | |
protected function createProgressBar() | |
{ | |
$bar = $this->output->createProgressBar(); | |
$bar->setEmptyBarCharacter('<fg=white>-</>'); | |
$bar->setBarCharacter('<fg=yellow>-</>'); | |
$bar->setProgressCharacter("\xF0\x9F\x94\xA5"); | |
$bar->setFormat(" %current%/%max% \xF0\x9F\xA5\x9A %bar% \xF0\x9F\x8D\xB3 %percent:3s%%\n%elapsed:6s% / %estimated:-6s% %memory:6s%"); | |
return $bar; | |
} | |
/** | |
* Clear previously displayed line | |
* | |
* @return void | |
*/ | |
protected function clearOutput() | |
{ | |
$this->output->write("\x0D"); | |
$this->output->write("\x1B[2K"); | |
$this->output->write("\x1B[1A\x1B[2K"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment