Task.php
TLDR
This file contains the implementation of a Task
class in the Illuminate\Console\View\Components
namespace. The class extends the Component
class and includes a render
method.
Methods
render
Renders the component using the given arguments. It takes three parameters:
-
$description
(string): The description of the task. -
$task
(callable): A callback function that represents the task to be executed. Defaults tonull
. -
$verbosity
(integer): The verbosity level for output. Defaults toOutputInterface::VERBOSITY_NORMAL
.
The render
method performs the following steps:
- Calls the
mutate
method from the parent class to modify the description with some mutators. - Calculates the width of the description.
- Writes the description to the output.
- Starts the timer for tracking the task execution time.
- Executes the task callback or a default callback if none is provided.
- Catches any exceptions thrown during the task execution and rethrows them.
- Calculates the runtime of the task in human-readable format.
- Determines the number of dots to display in the output based on the available width.
- Writes the dots and the runtime to the output.
- Writes the final status of the task (done or fail) to the output.
Classes
Task
A class that represents a task component. It extends the Component
class and provides the render
method for rendering the task.
<?php
namespace Illuminate\Console\View\Components;
use Illuminate\Support\InteractsWithTime;
use Symfony\Component\Console\Output\OutputInterface;
use Throwable;
use function Termwind\terminal;
class Task extends Component
{
use InteractsWithTime;
/**
* Renders the component using the given arguments.
*
* @param string $description
* @param (callable(): bool)|null $task
* @param int $verbosity
* @return void
*/
public function render($description, $task = null, $verbosity = OutputInterface::VERBOSITY_NORMAL)
{
$description = $this->mutate($description, [
Mutators\EnsureDynamicContentIsHighlighted::class,
Mutators\EnsureNoPunctuation::class,
Mutators\EnsureRelativePaths::class,
]);
$descriptionWidth = mb_strlen(preg_replace("/\<[\w=#\/\;,:.&,%?]+\>|\\e\[\d+m/", '$1', $description) ?? '');
$this->output->write(" $description ", false, $verbosity);
$startTime = microtime(true);
$result = false;
try {
$result = ($task ?: fn () => true)();
} catch (Throwable $e) {
throw $e;
} finally {
$runTime = $task
? (' '.$this->runTimeForHumans($startTime))
: '';
$runTimeWidth = mb_strlen($runTime);
$width = min(terminal()->width(), 150);
$dots = max($width - $descriptionWidth - $runTimeWidth - 10, 0);
$this->output->write(str_repeat('<fg=gray>.</>', $dots), false, $verbosity);
$this->output->write("<fg=gray>$runTime</>", false, $verbosity);
$this->output->writeln(
$result !== false ? ' <fg=green;options=bold>DONE</>' : ' <fg=red;options=bold>FAIL</>',
$verbosity,
);
}
}
}