2017 © Pedro Peláez
 

library console-wrapper

Wrapper class of symfony/console

image

hiroto-k/console-wrapper

Wrapper class of symfony/console

  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 3 Versions
  • 0 % Grown

The README.md

console-wrapper

Build Status PHP from Packagist Maintainability License, (*1)

Wrapper class of symfony/console, (*2)

Install

composer require hiroto-k/console-wrapper:^1.0, (*3)

Documents

Examples

Example Command class

<?php

namespace ExampleApp\Commands;

use HirotoK\ConsoleWrapper\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

/**
 * Command class of "greeting" command.
 */
class GreetingCommand extends Command
{
    /**
     * Definition the command name.
     *
     * @var string
     */
    protected $name = 'greeting';

    /**
     * Definition the command description.
     *
     * @var string
     */
    protected $description = 'Example greeting command with console-wrapper';

    /**
     * Setup the command class.
     */
    protected function setup()
    {
        // Setup class configure.
        // This method is called before the "configure" method.
    }

    /**
     * Execute the command.
     */
    protected function handle()
    {
        $greet = $this->option('hi') ? 'Hi, ' : 'Hello, ';

        $name = $this->argument('first-name');

        if ($this->hasArgument('family-name')) {
            $name .= ' '.$this->argument('family-name');
        }

        $this->writeln($greet.$name);
    }

    /**
     * Definition the command arguments.
     *
     * @see \Symfony\Component\Console\Command\Command::addArgument
     *
     * @return array
     */
    protected function commandArguments()
    {
        return [
            // [$name, $mode = null, $description = '', $default = null]
            ['first-name', InputArgument::REQUIRED, 'Your first name (required)'],
            ['family-name', InputArgument::OPTIONAL, 'Your family name (optional)'],
        ];
    }

    /**
     * Definition the command options.
     *
     * @see \Symfony\Component\Console\Command\Command::addOption
     *
     * @return array
     */
    protected function commandOptions()
    {
        return [
            // [$name, $shortcut = null, $mode = null, $description = '', $default = null]
            ['hi', null, InputOption::VALUE_NONE, 'Use "Hi".'],
        ];
    }
}

Example Application class

<?php

namespace ExampleApp;

use HirotoK\ConsoleWrapper\Application as WrapperApplication;
use Symfony\Component\Console\Input\InputOption;

/**
 * Customize application class.
 */
class Application extends WrapperApplication
{
    /**
     * Definition the global command options.
     *
     * @return array
     */
    protected function globalOptions()
    {
        return [
            // [$name, $shortcut = null, $mode = null, $description = '', $default = null]
            ['debug', null, InputOption::VALUE_NONE, 'Enable debug mode.'],
            ['config', 'c', InputOption::VALUE_REQUIRED, 'Set path of config file.', 'path/to/default'],
        ];
    }
}

Example execute file

<?php

use ExampleApp\Application;
use ExampleApp\Commands\GreetingCommand;

$application = new Application();

// Add command class.
$application->add(new GreetingCommand());

// Start the application.
$application->run();

Uses

Arguments

Definition the arguments, use the Command::commandArguments() method., (*4)

Returned array will pass to the Command::addArgument() method. See the documents for arguments of Command::addArgument() method., (*5)

/**
 * Definition the command arguments.
 *
 * @return array
 */
protected function commandArguments()
{
    return [
        // [$name, $mode = null, $description = '', $default = null]
        ['user-id', InputArgument::REQUIRED, 'User name (required)'],
        ['task', InputArgument::OPTIONAL, 'Task name (optional)', 'default'],
    ];
}

For the access to arguments, use the Command::argument() method., (*6)

If you need to all of the arguments, use the Command::arguments() method, (*7)

To checks if the arguments exists, use the Command::hasArgument() method., (*8)

protected function handle()
{
    // Get argument value.
    $userId = $this->argument('user-id');

    // Get all arguments.
    $allArguments = $this->arguments();

    // Checks whether a argument exists.
    $hasTaskArgument = $this->hasArgument('task');
}

Options

Definition the options, use the Command::commandOptions() method., (*9)

Returned array will pass to the Command::addOption() method. See the documents for arguments of Command::addOption() method., (*10)

/**
 * Definition the command options.
 *
 * @return array
 */
protected function commandOptions()
{
    return [
        // [$name, $shortcut = null, $mode = null, $description = '', $default = null]
        ['name', null, InputOption::VALUE_REQUIRED, 'User name.', 'default name'],
        ['force', null, InputOption::VALUE_NONE, 'Force execute.'],
    ];
}

For the access to options, use the Command::option() method., (*11)

If you need to all of the options, use the Command::options() method, (*12)

To checks if the options exists, use the Command::hasOption() method., (*13)

protected function handle()
{
    // Get option value.
    $name = $this->option('name');

    // Get all options.
    $allOptions = $this->options();

    // Checks whether a option exists.
    $hasForceOption = $this->hasOption('force');
}

Global options

console-wrapper can easily set global options., (*14)

<?php

namespace ExampleApp;

use HirotoK\ConsoleWrapper\Application as WrapperApplication;
use Symfony\Component\Console\Input\InputOption;

class Application extends WrapperApplication
{
    /**
     * Definition the global command options.
     *
     * @return array
     */
    protected function globalOptions()
    {
        return [
            // [$name, $shortcut = null, $mode = null, $description = '', $default = null]
            ['debug', null, InputOption::VALUE_NONE, 'Enable debug mode.'],
            ['config', 'c', InputOption::VALUE_REQUIRED, 'Set path of config file.', 'path/to/default'],
        ];
    }
}

Output

console-wrapper is provided some output methods., (*15)

protected function handle()
{
    // Display normal message.
    $this->writeln('message');
    $this->writeln([
        'multi',
        'line',
        'message',
    ]);

    // Display message with styles.
    $this->info('info style');
    $this->comment('comment style');
    $this->question('question style');
    $this->error('error style');
}

Auto add commands by PSR-4

If project using PSR-4, auto load all commands by Application::loadByPsr4() method., (*16)

/**
 * Auto add commands by PSR-4.
 * 
 * loadByPsr4(string $nameSpacePrefix, string $targetDir)
 */
$application->loadByPsr4("\ExampleApp\Commands", realpath(__DIR__.'/src/Commands'));

Logger

console-wrapper can easily use the logger., (*17)

Sets the logger instance in the execute file. Logger class must be implemented the \Psr\Log\LoggerInterface interface., (*18)

/**
 * Set logger instance to application and command class.
 */
$application->setLogger($logger);

In the command class, use the logger() method and use the logger., (*19)

protected function handle()
{
    $this->logger()->debug('Debug message');
    $this->logger()->error('Error message');
}

Default logger

If logger instance not sets in application, default using the \Psr\Log\NullLogger class., (*20)

\Psr\Log\NullLogger, (*21)

protected function handle()
{
    // Output Psr\Log\NullLogger
    $this->writeln(get_class($this->logger()));
}

Override the default logger

If you want override the default logger, please override the Application::createDefaultLogger() method. Return instance must be implemented the \Psr\Log\LoggerInterface interface., (*22)

// Use monolog in default logger

use HirotoK\ConsoleWrapper\Application as WrapperApplication;
use Monolog\Logger;

class Application extends WrapperApplication
{
    /**
     * Override default logger instance.
     * Return instance must be implement the \Psr\Log\LoggerInterface
     * 
     * @return \Monolog\Logger
     */
    protected function createDefaultLogger()
    {
        return new Logger();
    }
}

Using logger in Command::setup

If using the logger in Command::setup() method, must be sets the logger instance before commands add., (*23)

// Register logger instance
$application->setLogger($logger);

// Add commands
$application->add(new GreetingCommand());
$application->loadByPsr4("\ExampleApp\Commands", realpath(__DIR__.'/src/Commands'));

Helpers and Utils

Confirm question

Simple confirmation. Default returns true., (*24)

protected function handle()
{
    if ($this->confirm('continue ? (y/n) ')) {
        // If enter y
    }
}

sets default value, (*25)

protected function handle()
{
    if ($this->confirm('continue ? (y/n) ', false)) {
        // If enter y
    }
}

Call other command

Call other command in command class., (*26)

protected function handle()
{
    // Call the "other-command-name" command
    $this->callCommand('other-command-name');
}

with parameters, (*27)

protected function handle()
{
    // Call the "other-command-name" command, with name parameter
    $this->callCommand('other-command-name', ['name' => 'example']);
}

Render tables

protected function handle()
{
    // Only creates Table class instance.
    $table = $this->createTable();

    // Sets headers and rows
    $headers = ['name', 'location'];
    $rows = [
        ['Hoge', 'jp'],
        ['Foo', 'us'],
    ];
    $table = $this->createTable($headers, $rows)

    // Render table
    $table->render();
}
+------+----------+
| name | location |
+------+----------+
| Hoge | jp       |
| Foo  | us       |
+------+----------+

customize tables, place see the \Symfony\Component\Console\Helper\Table class., (*28)

// Set the column width.
$this
    ->createTable($headers, $rows)
    ->setColumnWidth(0, 10)
    ->render();

Progress Bar

protected function handle()
{
    $progressBar = $this->createProgressBar(100);

    $progressBar->start();

    $i = 0;
    while ($i++ < 100) {
        $progressBar->advance();
    }

    $progressBar->finish();
}

customize progress bar, place see the \Symfony\Component\Console\Helper\ProgressBar class., (*29)

Gets a helper instance

protected function handle()
{
    // Get the question helper instance
    $this->getQuestionHelper();

    // Get the process helper instance.
    $this->getProcessHelper();
}

License

MIT License, (*30)

The Versions

21/07 2018

dev-master

9999999-dev

Wrapper class of symfony/console

  Sources   Download

MIT

The Requires

 

The Development Requires

05/07 2018

1.1.0

1.1.0.0

Wrapper class of symfony/console

  Sources   Download

MIT

The Requires

 

The Development Requires

23/06 2018

1.0.0

1.0.0.0

Wrapper class of symfony/console

  Sources   Download

MIT

The Requires

 

The Development Requires