PHP code example of snicco / better-wp-cli

1. Go to this page and download the library: Download snicco/better-wp-cli library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

snicco / better-wp-cli example snippets


use Snicco\Component\BetterWPCLI\Command;
use Snicco\Component\BetterWPCLI\Input\Input;
use Snicco\Component\BetterWPCLI\Output\Output;
use Snicco\Component\BetterWPCLI\Synopsis\Synopsis;
use Snicco\Component\BetterWPCLI\Synopsis\InputFlag;
use Snicco\Component\BetterWPCLI\Synopsis\InputOption;
use Snicco\Component\BetterWPCLI\Synopsis\InputArgument;

class ExampleCommand extends Command {
    
    // You can set an explicit command name. 
    // If a command name is not set explicitly, it's determined from the class name.
    protected static string $name = 'example';
    
    
    
    // The short description of the command that will be shown
    // when running "wp help example"
    protected static string $short_description = 'Prints a greeting'
    
    
    
    // If a long description is not set explicitly it will default to 
    // the short_description property.
    protected static string $long_description = '## EXAMPLES' . "\n\n" . 'wp example hello Newman'
    
    
    
    public function execute(Input $input, Output $output) : int {
        
        $name = $input->getArgument('name'); // (string) Always a string
        $type = $input->getOption('flag'); // (string) Always a string
        $honk = $input->getFlag('honk'); // (bool) Always a boolean
        
        // outputs a message followed by a "\n"
        $output->writeln("$type: Hello $name!");
        
        // Writes directly to the output stream without newlines
        //$output->write('You are about');
        //$output->write(' to honk');
        
        // Writes to "\n" chars
        //$output->newLine(2);
        
        if($honk) {
            $output->writeln("Honk");
        }
        
        // (This is equivalent to returning int(0))
        return Command::SUCCESS;

        // (This is equivalent to returning int(1))
        // return Command::FAILURE;

        // (This is equivalent to returning int(2))
        // return Command::INVALID
    }
    
    
    public static function synopsis() : Synopsis{
      
      return new Synopsis(
            new InputArgument(
                'name', 
                'The name of the person to great', 
                InputArgument::REQUIRED
            ),
            
            // You can combine options by using bit flags.
            
            // new InputArgument(
            //    'some-other-arg', 
            //    'This is another arg', 
            //    InputArgument::REQUIRED | InputArgument::REPEATING
            //),
            
            new InputOption(
                'type', 
                'Whether or not to greet the person with success or error.', 
                InputOption::OPTIONAL, 
                'success',
                ['success', 'error']
            ),
            new InputFlag('honk')
      );
      
    }
    
}


use Snicco\Component\BetterWPCLI\Command;
use Snicco\Component\BetterWPCLI\Synopsis\Synopsis;
use Snicco\Component\BetterWPCLI\Synopsis\InputArgument;

class MyCommand extends Command {

    public static function synopsis() : Synopsis{
        return parent::synopsis()->with([
            new InputArgument(
                'name', 
                'The name of the person to great', 
                InputArgument::REQUIRED
            ),
        ]);
    }
}


if(!defined('WP_CLI')) {
    return;
}

use Snicco\Component\BetterWPCLI\WPCLIApplication;
use Snicco\Component\BetterWPCLI\CommandLoader\ArrayCommandLoader;

// The namespace will be prepended to all your commands automatically.
$command_namespace = 'snicco';

// The command loader is responsible for lazily loading your commands.
// The second argument is a callable that should return an instance of
// a command by its name. This should typically be a call to your dependency injection container.

// This array can come from a configuration file.
$command_classes = [
    ExampleCommand::class,
    FooCommand::class,
    BarCommand::class,
];

$container = /* Your dependency injection container or another factory class */
$factory = function (string $command_class) use ($container) {
    return $container->get($command_class);
}

$command_loader = new ArrayCommandLoader($command_classes, $factory);

$application = new WPCLIApplication($command_namespace);

$application->registerCommands();

use Snicco\Component\BetterWPCLI\Input\Input
use Snicco\Component\BetterWPCLI\Output\Output
use Snicco\Component\BetterWPCLI\Synopsis\Synopsis;
use Snicco\Component\BetterWPCLI\Synopsis\InputFlag;
use Snicco\Component\BetterWPCLI\Synopsis\InputOption;
use Snicco\Component\BetterWPCLI\Synopsis\InputArgument;

// ...
public static function synopsis(): Synopsis
{
    return new Synopsis(
        new InputArgument(
            'role',
            'The role that should be assigned to the users',
        ),
        new InputArgument(
            'ids',
            'A list of user ids that should be assigned to passed role',
            InputArgument::REQUIRED | InputArgument::REPEATING
        ),
        new InputFlag(
            'notify',
            'Send the user an email about his new role'
        ),
        new InputOption(
            'some-option',
        ),
    );
}

// ...
public function execute(Input $input, Output $output): int
{
    $output->writeln([
        'Changing user roles',
        '===================',
    ]);
    
    // Arguments are retrieved by their name.
    $role = $input->getArgument('role');  // (string)
    
    // The second argument is returned if the option/argument was not passed. 
    $option = $input->getOption('some-option', 'some-default-value'); // (string)
    
    $users = $input->getRepeatingArgument('ids'); // (string[]) and array of ids.
    
    $notify = $input->getFlag('notify', false);
    
    foreach($users as $id) {
        
        // assign role here
        if($notify) {
            // send email here
        }
    }            
    
        
    return Command::SUCCESS;
}

use Snicco\Component\BetterWPCLI\Input\Input
use Snicco\Component\BetterWPCLI\Output\Output

// ...
protected function execute(Input $input, Output $output): int
{
    // outputs multiple lines to the console (adding "\n" at the end of each line)
    $output->writeln([
        'Starting the command',
        '============',
        '',
    ]);

    // outputs a message followed by a "\n"
    $output->writeln('Doing something!');

    // outputs a message without adding a "\n" at the end of the line
    $output->write('You are about to ');
    $output->write('do something here');
    
    // Outputs 3 "\n" chars.
    $output->newLine(3);    
    
    // You can also use the WP_CLI class. 
    // WP_CLI::debug('doing something');
        
    return Command::SUCCESS;
}

use Snicco\Component\BetterWPCLI\Command;
use Snicco\Component\BetterWPCLI\Verbosity;
use Snicco\Component\BetterWPCLI\Input\Input;
use Snicco\Component\BetterWPCLI\Output\Output;

class AssignUserRoles extends Command {
    
    public function execute(Input $input,Output $output) : int{
        
        $output->writeln('Always printed', Verbosity::QUIET);
        
        $output->writeln('only printed for verbosity normal and above', Verbosity::NORMAL);
        
        $output->writeln('only printed for verbosity verbose and above', Verbosity::VERBOSE);
        
        $output->writeln('only printed for verbosity very-verbose and above', Verbosity::VERY_VERBOSE);
        
        $output->writeln('only printed for verbosity debug', Verbosity::DEBUG);
        
        return Command::SUCCESS;
    }
    
    // .. synopsis defined here.
    
}


use Snicco\Component\BetterWPCLI\Command;
use Snicco\Component\BetterWPCLI\Style\SniccoStyle;
use Snicco\Component\BetterWPCLI\Input\Input;
use Snicco\Component\BetterWPCLI\Output\Output;

   // ... 
   protected function execute(Input $input, Output $output): int
    {
        $io = new SniccoStyle($input, $output);
        // ...
        
        // Not so important information
        //$io->title('Command title);
        
        $output->writeln('Some important command output that should be piped.'); 
        
        return Command::SUCCESS;
    }


$io->title('This is the command title');

$io->section('This is a new section');

$io->info('This is an info');

$io->note('This is a note');

// Passing an array is optional.
$io->text(['This is a text', 'This is another text']);

// Passing an array is optional.
$io->success(['This command', 'was successful']);

// Passing an array is optional.
$io->warning(['This command', 'displays a warning']);

// Passing an array is optional.
$io->error(['This command', 'did not work']);

use Snicco\Component\BetterWPCLI\Command;
use Snicco\Component\BetterWPCLI\Style\SniccoStyle;
use Snicco\Component\BetterWPCLI\Input\Input;
use Snicco\Component\BetterWPCLI\Output\Output;

   // ... 
   protected function execute(Input $input, Output $output): int
    {
        $io = new SniccoStyle($input, $output);
        
        // The second argument is the default value
        if(!$io->confirm('Are you sure that you want to continue', false)) {
        
            $io->warning('Command aborted');
            
            return Command::SUCCESS;
        }
        // Proceed
        
        return Command::SUCCESS;
    }


use Snicco\Component\BetterWPCLI\Command;
use Snicco\Component\BetterWPCLI\Style\SniccoStyle;
use Snicco\Component\BetterWPCLI\Input\Input;
use Snicco\Component\BetterWPCLI\Output\Output;

   // ... 
   protected function execute(Input $input, Output $output): int
    {
        $io = new SniccoStyle($input, $output);
        
        $domain = $io->ask('Please tell use your company domain', 'snicco.io');
        
        $output->writeln('Your domain is: '. $domain);
    }

use Snicco\Component\BetterWPCLI\Command;
use Snicco\Component\BetterWPCLI\Style\SniccoStyle;
use Snicco\Component\BetterWPCLI\Input\Input;
use Snicco\Component\BetterWPCLI\Output\Output;
use Snicco\Component\BetterWPCLI\Output\Output;
use Snicco\Component\BetterWPCLI\Question\Question;

   // ... 
   protected function execute(Input $input, Output $output): int
    {
        $io = new SniccoStyle($input, $output);
        
        // This will fall back to visible input if stty is not available.
        // e.g. on Windows
        $secret = $io->askHidden('What is your secret?')
        
        $question = (new Question('What is your secret'))
                        ->withHiddenInput()
                        ->withFallbackVisibleInput(false);
        
        // This will throw an exception if hidden input can not be ensured.
        $secret = $io->askQuestion($question);
        
        //
    }

use Snicco\Component\BetterWPCLI\Command;
use Snicco\Component\BetterWPCLI\Style\SniccoStyle;
use Snicco\Component\BetterWPCLI\Input\Input;
use Snicco\Component\BetterWPCLI\Output\Output;
use Snicco\Component\BetterWPCLI\Output\Output;
use Snicco\Component\BetterWPCLI\Question\Question;
use Snicco\Component\BetterWPCLI\Exception\InvalidAnswer;

   // ... 
   protected function execute(Input $input, Output $output): int
    {
        $io = new SniccoStyle($input, $output);
        
        $validator = function (string $answer) :void {
            if(strlen($answer) < 5) {
                throw new InvalidAnswer('The name must have at least 6 characters.');
            }
        };
        
        $attempts = 2; 
                
        $question = new Question('Please enter a name', 'default_name', $validator, $attempts);
        
        $answer = $io->askQuestion($question);
    }

use Snicco\Component\BetterWPCLI\WPCLIApplication;;

$command_loader = new ArrayCommandLoader($command_classes, $factory);

$application = new WPCLIApplication($command_namespace);

// This disables exception handling.
//All exceptions are now handled globally by WordPress again.
$application->catchException(false);

$application->registerCommands();

use Snicco\Component\BetterWPCLI\Command;
use Snicco\Component\BetterWPCLI\Style\SniccoStyle;
use Snicco\Component\BetterWPCLI\Input\Input;
use Snicco\Component\BetterWPCLI\Output\Output;

   // ... 
   protected function execute(Input $input, Output $output): int
    {
        $arr = ['foo'];
        
        $foo = $arr[1];
        
        //
        
        return Command::SUCCESS;
    }


use Snicco\Component\BetterWPCLI\WPCLIApplication;;

$command_loader = new ArrayCommandLoader($command_classes, $factory);

$application = new WPCLIApplication($command_namespace);

// This is the default setting
$application->throwExceptionsAt(E_ALL);

// Throw exceptions for all errors expect deprecations.
$application->throwExceptionsAt(E_ALL - E_DEPRECATED - E_USER_DEPRECATED);

// This disables the behaviour entirely (NOT RECOMMENDED)
$application->throwExceptionsAt(0);

$application->registerCommands();

use Snicco\Component\BetterWPCLI\Testing\CommandTester;

$tester = new CommandTester(new CreateUserCommand());

$tester->run(['calvin', '[email protected]'], ['send-email' => true]);

$tester->assertCommandIsSuccessful();

$tester->assertStatusCode(0);

$tester->seeInStdout('User created!');

$tester->dontSeeInStderr('Fail');