Mixins (i.e., Traits)¶
CliColor¶
This is an opinionated trait that you can include with your CLI apps based on Symfony Console. It makes a number of tags available for use with $output->writeln();
In this example, we define the <done> tag using the built-in formatter (provided by Skyzyx\Shared\Mixin\CliColor), and can use it as part of our output.
namespace MyApp\Command;
use Skyzyx\Shared\Mixin\CliColor;
use Skyzyx\Shared\Utility\File;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
abstract class AbstractCommand extends Command
{
use CliColor;
protected function interact(InputInterface $input, OutputInterface $output)
{
$output->getFormatter()->setStyle('done', self::formatter()->pending);
$output->writeln(sprintf('<done> Done (%s) </done>',
File::formatSize(memory_get_peak_usage())
));
}
}
ResponseHandler¶
This is an opinionated trait that you can include with your CLI apps based on Symfony Console. It takes your array or Pimple\Container input and wraps the key-value pairs in an ASCII table — being intelligent about how it’s handled (handles the work of converting a list into a series of dictionaries).
In this example, we make an HTTP request to the World’s Best API, which returns either a dictionary (i.e., JSON object) or a list (i.e., JSON array). You should know which type of response the API return and can decide whether to display a single table of key-value pairs, or multiple tables.
namespace MyApp\Command;
use GuzzleHttp\Client as HTTP;
use Skyzyx\Shared\Mixin\Table;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class MyCommand extends Command
{
use Table;
protected function interact(InputInterface $input, OutputInterface $output)
{
$http = new HTTP();
$response = $http->get('https://worlds-best-api.com/gimme-an-array');
$key = 'object_id';
// self::handleResponse($response, $output, $key);
self::handleArrayResponse($response, $output, $key);
}
}
Table¶
This is an opinionated trait that you can include with your CLI apps based on Symfony Console. It takes your array or Pimple\Container input and wraps the key-value pairs in an ASCII table (provided the input is a dictionary, not a list).
In this example, we make an HTTP request to the World’s Best API, which returns a dictionary (i.e., JSON object, as opposed to a JSON array).
namespace MyApp\Command;
use GuzzleHttp\Client as HTTP;
use Skyzyx\Shared\Mixin\Table;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class MyCommand extends Command
{
use Table;
protected function interact(InputInterface $input, OutputInterface $output)
{
$http = new HTTP();
$response = $http->get('https://worlds-best-api.com');
self::asTable($response->json(), $output);
}
}