Skip to content

Task arguments

When creating a function that will be used as a task, all the parameters of the function will be used as arguments or options:

use Castor\Attribute\AsTask;

use function Castor\io;

#[AsTask()]
function task(
    string $firstArg,
    string $secondArg
) {
    io()->writeln($firstArg . ' ' . $secondArg);
}

Which can be called like that:

$ castor task foo bar
foo bar

Optional arguments

You can make an argument optional by giving it a default value:

use Castor\Attribute\AsTask;

use function Castor\io;

#[AsTask()]
function task(
    string $firstArg,
    string $secondArg = 'default'
) {
    io()->writeln($firstArg . ' ' . $secondArg);
}
$ castor task foo
foo default
$ castor task --default=bar foo
foo bar

Arguments without configuration nor validation

Castor supports the use of arguments without any configuration nor validation. For example, when you want to call a sub-process:

#[AsTask(ignoreValidationErrors: true)]
function phpunit(#[AsRawTokens] array $rawTokens): void
{
    run(['phpunit', ...$rawTokens]);
}

Then, you can use it like that:

$ castor phpunit --filter=testName --debug --verbose

Tip

Related example: args.php

Overriding the argument name and description

You can override the name and description of an argument by using the Castor\Attribute\AsArgument attribute:

use Castor\Attribute\AsArgument;
use Castor\Attribute\AsTask;

use function Castor\io;

#[AsTask()]
function command(
    #[AsArgument(name: 'foo', description: 'This is the foo argument')]
    string $arg = 'bar',
) {
    io()->writeln($arg);
}
$ castor command foo
foo

Tip

Related example: args.php

Overriding the option name and description

If you prefer, you can force an argument to be an option by using the Castor\Attribute\AsOption attribute:

use Castor\Attribute\AsOption;
use Castor\Attribute\AsTask;

use function Castor\io;

#[AsTask()]
function command(
    #[AsOption(name: 'foo', description: 'This is the foo option')]
    string $arg = 'bar',
) {
    io()->writeln($arg);
}
$ castor command --foo=foo
foo

You can also configure the mode of the option. The mode determines how the option must be configured:

use Castor\Attribute\AsOption;
use Castor\Attribute\AsTask;

use function Castor\run;

#[AsTask()]
function command(
    #[AsOption(description: 'This is the foo option', mode: InputOption::VALUE_NONE)]
    bool $force,
) {
    if ($force) {
        io()->writeln('command has been forced');
    }
}
$ castor command --force
command has been forced

Tip

Related example: args.php


Please refer to the Symfony documentation for more information.