PHP code example of tarsana / command

1. Go to this page and download the library: Download tarsana/command 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/ */

    

tarsana / command example snippets



Tarsana\Command\Command;

class HelloWorld extends Command {

    protected function execute()
    {
        $this->console->line('Hello World');
    }

}

(new HelloWorld)->run();


class HelloWorld extends Command {

	protected function init ()
	{
		$this->name('Hello World')
		     ->version('1.0.0-alpha')
		     ->description('Shows a "Hello World" message');
	}

    protected function execute()
    {
        $this->console->line('Hello World');
    }

}

$this->name('blabla'); // will set the name to 'blabla' and return $this
$this->name(); // calling it without parameter will get the value of name

protected function execute()
{
    $this->console->out('Your name: ');
    $name = $this->console->readLine();
    $this->console->line("Hello {$name}");
}

$this->console->line('<background:15><color:19>Blue text on white background<reset>');
$this->console->line('<background:124><color:15>White text on red background<reset>');

$this->console->alias('<danger>', '<background:124><color:15><bold>');
$this->console->alias('</danger>', '<reset>');

$this->console->line('<danger>Some text</danger>');
// is equivalent to
$this->console->line('<background:124><color:15><bold>Some text<reset>');

$this->console->line('<info> information text </info>');
$this->console->line('<warn> warning text </warn>');
$this->console->line('<success> success text </success>');
$this->console->line('<error> error text </error>');
$this->console->line('<tab>'); // prints four spaces "    "
$this->console->line('<br>'); // prints line break  PHP_EOL

class RepeatCommand extends Command {

    protected function init ()
    {
        $this->name('Repeat')
             ->version('1.0.0')
             ->description('Repeats a word a number of times')
             ->syntax('word: string, count: (number: 3)')
             ->options(['--upper'])
             ->describe('word', 'The word to repeat')
             ->describe('count', 'The number of times to repeat the word')
             ->describe('--upper', 'Converts the result to uppercase');
    }

    protected function execute()
    {
        $result = str_repeat($this->args->word, $this->args->count);
        if ($this->option('--upper'))
            $result = strtoupper($result);
        $this->console->line($result);
    }

}

class ClassGenerator extends Command {
    protected function init()
    {
        $this->name('Class Generator')
        ->version('1.0.0')
        ->description('Generates basic code for a class.')
        ->syntax('
            language: string,
            name: string,
            parents: ([string]:[]),
            interfaces: ([string]:[]),
            attrs: [{
                name,
                type,
                hasGetter: (boolean:true),
                hasSetter: (boolean:true),
                isStatic: (boolean:false)
            }],
            methods: ([{
                name: string,
                type: string,
                args: [{ name, type, default: (string:null) |.}],
                isStatic: (boolean:false)
            }]:[])
        ')
        ->descriptions([
            'language'          => 'The programming language in which the code will be generated.',
            'name'              => 'The name of the class.',
            'parents'           => 'List of parent classes names.',
            'interfaces'        => 'List of implemented interfaces.',
            'attrs'             => 'List of attributes of the class.',
            'attrs.name'        => 'The name of the attribute.',
            'attrs.type'        => 'The type of the attribute.',
            'attrs.hasGetter'   => 'Generate a getter for the attribute.',
            'attrs.hasSetter'   => 'Generate a setter for the attribute.',
            'attrs.isStatic'    => 'The attribute is static.',
            'methods'           => 'List of methods of the class.',
            'methods.name'      => 'The method name.',
            'methods.type'      => 'The method return type.',
            'methods.args'      => 'List of arguments of the method.',
            'methods.isStatic'  => 'This method is static.'
        ]);
    }

    protected function execute()
    {
        $this->console->line("Generate code for the class {$this->args->name} in {$this->args->language}...");

    }
}

using Tarsana\IO\Filesystem;
// ...
protected function init()
{
	$this->fs(new Filesystem('path/to/directory/you/want'));
}

class ConfigCommand extends Command {
    protected function init()
    {
        // ...
        $this->configPaths(['/home/user/.config.json', 'config.json']);
    }

    protected function execute()
    {
        // getting a config value
        // assuming that $data is the merged content of the config files
        $this->config('name'); // returns $data['name']
        $this->config('foo.bar.baz'); // returns $data['foo']['bar']['baz']
        $this->config(); // returns $data
    }
}


Tarsana\Command\Command;
use Tarsana\Command\Templates\TwigTemplateLoader;


class RenderHelloCommand extends Command {

    protected function init ()
    {
        $this
            ->name('Renders Simple Template')
            ->description('Renders a simple twig template')
            ->syntax('name: (string:You)')
            ->describe('name', 'Your name')
            ->templatesPath(__DIR__.'/templates'); // defines the path to the templates
    }

    protected function execute()
    {
        $message = $this->template('hello')
            ->render([
                'name' => $this->args->name
            ]);

        $this->console->line($message);
    }

}

(new RenderHelloCommand)->run();

// ...
protected function init()
{
    //...
    // Assuming that FooCommand and BarCommand are already defined
    $this->command('foo', new FooCommand)
         ->command('bar', new BarCommand); // this erases the subcommand with key 'bar' if exists
    // Or set all subcommands at once (this will erase any previous subcommands)
    $this->commands([
        'foo' => new FooCommand,
        'bar' => new BarCommand
    ]);

    // Later on you can get subcommands
    $this->commands(); // returns all the subcommands as key-value array
    $this->command('name'); // gets the subcommand with the given name
    // will throw an exception if the subcommand is missing
    $this->hasCommand('name'); // checks if a subcommand with the given name exists
}

use Tarsana\Tester\CommandTestCase;

class HelloWorldTest extends CommandTestCase {

    public function test_it_prints_hello()
    {
        $this->withStdin("Amine\n")
             ->command(new HelloWorld)
             ->prints("Your name:")
             ->prints("Hello Amine<br>");
    }

    public function test_it_shows_hello_world_version()
    {
        $this->command(new HelloWorld, ['--version'])
             ->printsExactly("<info>Hello World</info> version <info>1.0.0-alpha</info><br>");
    }

}

withStdin(string $content) : CommandTestCase;

command(Command $c, array $args = []) : CommandTestCase;

printsExactly(string $text) : CommandTestCase;
prints(string $text) : CommandTestCase;
printsError(string $text) : CommandTestCase;

class RepeatCommandTest extends CommandTestCase {

    public function test_it_repeats_word_three_times()
    {
        $this->command(new RepeatCommand, ['foo'])
             ->argsEqual((object) [
                'word' => 'foo',
                'count' => 3
             ])
             ->optionsEqual([
                '--upper' => false
             ])
             ->printsExactly("foofoofoo<br>");
    }

    public function test_it_repeats_word_n_times_uppercase()
    {
        $this->command(new RepeatCommand, ['bar', '5', '--upper'])
             ->argsEqual((object) [
               'word' => 'bar',
               'count' => 5
             ])
             ->optionsEqual([
               '--upper' => true
             ])
             ->printsExactly("BARBARBARBARBAR<br>");
    }
}

argsEqual(object $args) : CommandTestCase;
optionsEqual(array $options) : CommandTestCase;

class ListCommand extends Command {

    protected function init ()
    {
        $this->name('List')
             ->version('1.0.0-alpha')
             ->description('Lists files and directories in the current directory.');
    }

    protected function execute()
    {
        foreach($this->fs->find('*')->asArray() as $file) {
            $this->console->line($file->name());
        }
    }

}

class ListCommandTest extends CommandTestCase {

    public function test_it_lists_files_and_directories()
    {
        $this->havingFile('demo.txt', 'Some text here!')
             ->havingFile('doc.pdf')
             ->havingDir('src')
             ->command(new ListCommand)
             ->printsExactly('demo.txt<br>doc.pdf<br>src<br>');
    }

    public function test_it_prints_nothing_when_no_files()
    {
        $this->command(new ListCommand)
             ->printsExactly('');
    }
}

havingFile(string $path, string $content = '') : CommandTestCase;
havingDir(string $path) : CommandTestCase;

$ php hello.php
Hello World

$ php hello.php
Your name: Amine
Hello Amine

$ php repeat.php foo 5
foofoofoofoofoo
$ php repeat.php bar --upper
BARBARBAR

$ php class.php  PHP User  Serializable name:string:true:true:false

render-hello.php
templates/
    hello.twig

$ php render-hello.php Foo
Hello Foo

$ php render-hello.php
Hello You

$ php your-script.php foo other arguments here