ctrl/console-helpers

一套为 Symfony2 Console 组件提供的控制台助手

v0.1.3 2014-05-12 16:30 UTC

This package is not auto-updated.

Last update: 2024-09-14 14:56:54 UTC


README

Symfony Console 组件的助手集合。

安装

"require": {
    "ctrl/console-helpers": "~1.0@dev"
}

助手

TableGeneratorHelper

用法

注册助手

/** @var \Symfony\Component\Console\Application $app */
$app->getHelperSet()->set(new \Ctrl\Console\Helper\TableGeneratorHelper());

生成表格

public function execute(InputInterface $input, OutputInterface $output)
{
    // Retrieve the Helper from the HelperSet
    $tableGenerator = $this->getHelperSet()->get('table_generator');

    /** @var \Traversable $data */
    $data = getATraversable();

    // Pass $output to the Generator to render the table immediately.
    $tableGenerator->generate($data, $output);

    // Or, don't, and the generator will return the table instead.
    $table = $tableGenerator->generate($data);
    $table->render($output);
}

映射器

您可以在生成器的第三个参数中传递一个 callable,以在将行添加到表格之前映射每一行。

public function execute(InputInterface $input, OutputInterface $output)
{
    // ...

    $mapper = function($row) {
        return [ 'a', 'b', 'c' ];
    };

    // Apply the mapper to the results
    $tableGenerator->generate($data, $output, $mapper);

    /*
    Output:
    +---+---+---+
    | 0 | 1 | 2 |
    +---+---+---+
    | a | b | c |
    | a | b | c |
    | a | b | c |
    | a | b | c |
    +---+---+---+
    */
}

CsvGeneratorHelper

用法

注册助手

/** @var \Symfony\Component\Console\Application $app */
$app->getHelperSet()->set(new \Ctrl\Console\Helper\CsvGeneratorHelper());

在您的命令定义中配置一个 to-csv 选项,以将 csv 文件名作为参数提供

public function configure()
{
    $this->setDefinition([
        new InputOption('to-csv', null, InputOption::VALUE_OPTIONAL, 'The CSV filename')
    ]);

然后,在 execute 期间调用生成器

public function execute(InputInterface $input, OutputInterface $output)
{
    // Retrieve the Helper from the HelperSet
    $csvGenerator = $this->getHelperSet()->get('csv_generator');

    /** @var \Traversable $data */
    $data = getATraversable();

    // Generate the CSV. The user will be prompted for the filename if it has not yet been provided.
    $csvGenerator->generate($data, $output);
}

映射器

CsvGeneratorHelper 还包括在将行插入之前应用映射的能力。有关详细信息,请参阅 TableGeneratorHelper 的映射器部分。

文件名

如果您想在生成时指定文件名,或者您正在使用非交互式模式,可以将文件名作为 generate 方法的第四个参数传递。

public function execute(InputInterface $input, OutputInterface $output)
{
    // ...

    // Generate the CSV with a specific filename.
    $csvGenerator->generate($data, $output, null, '/path/to/my.csv');
}