Symfony 8.2 is a big release for terminal applications. We already introduced console sub-commands, the Tui component improvements and the smarter arguments of invokable commands. This article showcases the rest of the new features added to the Console component.

Lists of Enums in Arguments and Options

Zoran Shefot Bogoevski Nicolas Grekas
Contributed by Zoran Shefot Bogoevski and Nicolas Grekas in #66622 and #66770

Invokable commands already map the value of an argument or option to a backed enum when you type it as such. However, arguments and options that accept several values gave you an array of strings, so you had to convert and validate their values yourself. In Symfony 8.2, type them as a list of backed enums and Symfony maps each value for you:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/Command/ExportTicketsCommand.php
use App\Enum\TicketStatus;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Attribute\Option;

#[AsCommand('app:tickets:export', description: 'Exports the tickets of an event')]
class ExportTicketsCommand
{
    public function __invoke(
        #[Option(description: 'Only the tickets with these statuses')]
        TicketStatus ...$status,
    ): int {
        // $status = [TicketStatus::Pending, TicketStatus::Paid]

        // ...
    }
}

The cases of the enum are suggested by the shell completion and a wrong value fails with an error that lists the supported ones.

If you prefer an array parameter, narrow it to the enum with PHPDoc, using either the list<TicketStatus> or the TicketStatus[] syntax. This is also the way to do it in the properties of #[MapInput] classes, which can't be variadic:

1
2
/** @param TicketStatus[] $status */
public function __invoke(#[Option] array $status = []): int

In addition, the help of the command now lists the values accepted by any argument or option mapped to an enum or to a list of enums. Before, you only saw them after passing a wrong value:

1
2
3
4
5
6
$ php bin/console app:tickets:export --help

# ...
Options:
  --status=STATUS  Only the tickets with these statuses [possible values:
                   pending, paid, expired] (multiple values allowed)

Hidden and Deprecated Options

FK
Contributed by FK in #54439

Commands can be hidden from the list of commands, but there was nothing similar for options. Also, when renaming an option, there was no way to warn the users of the old one. Symfony 8.2 adds two new option modes, which you can combine with the existing VALUE_* modes:

1
2
3
4
5
6
7
use Symfony\Component\Console\Input\InputOption;

$this
    ->addOption('output', 'o', InputOption::VALUE_REQUIRED | InputOption::DEPRECATED, 'Use --target instead')
    ->addOption('target', null, InputOption::VALUE_REQUIRED, 'The directory of the exported files')
    ->addOption('child-process', null, InputOption::VALUE_NONE | InputOption::HIDDEN, 'Used internally when the command spawns itself')
;

Invokable commands define them with the #[Option] attribute:

1
2
3
4
5
6
7
public function __invoke(
    #[Option(shortcut: 'o', deprecated: true)] ?string $output = null,
    #[Option] ?string $target = null,
    #[Option(hidden: true)] bool $childProcess = false,
): int {
    // ...
}

Both kinds of options keep working as before. The difference is how Symfony displays them:

  • Hidden options are not included in the command synopsis, in the help (in any of its formats) or in shell completion. Run the help command with the new --show-hidden-options option to list them;
  • Deprecated options are prefixed with [deprecated] in the help. When you pass one of them, the command writes a warning like The option "--output|-o" is deprecated. to the error output, so it doesn't mix with the output of the command.

Computed Descriptions in Console Attributes

Dawid Nowak
Contributed by Dawid Nowak in #61677

The arguments of PHP attributes must be constant expressions, so you can't call a function to build them. That's a problem for descriptions that depend on other values, such as the list of supported formats. In Symfony 8.2, the description of #[Argument] and #[Option], and the description and help of #[AsCommand] also accept a callable that returns the string:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/Command/ExportReportCommand.php
namespace App\Command;

use App\Report\ReportExporter;
use Symfony\Component\Console\Attribute\Argument;
use Symfony\Component\Console\Attribute\AsCommand;

#[AsCommand('app:report:export')]
class ExportReportCommand
{
    public function __invoke(
        // if the closure is complex, move its code to a static method and
        // use the first-class callable syntax: self::describeFormat(...)
        #[Argument(description: static function (): string {
            return 'One of: '.implode(', ', ReportExporter::SUPPORTED_FORMATS);
        })]
        string $format,
    ): int {
        // ...
    }
}

Both syntaxes require PHP 8.5, the first version that allows closures in constant expressions. If your application uses a previous PHP version, move that logic to a public static method of the command and reference it with the array syntax:

1
2
#[Argument(description: [self::class, 'describeFormat'])]
string $format,

A string is always the description itself, even if it matches the name of a function, so you can't define the callable as a string.

Help That Fits the Terminal Width

Aggelos Bellos
Contributed by Aggelos Bellos in #63784

The help and the list of commands displayed each description on a single line, which narrow terminals cut in the middle of a word and continued at the left edge. In Symfony 8.2, descriptions wrap at the terminal width and stay aligned next to the name they describe:

1
2
3
4
5
6
Options:
  -t, --target=TARGET  The directory where the exported
                       files are saved. It's created if
                       it doesn't exist
      --dry-run        Show the files that would be
                       exported without writing them

GitLab Format for lint:yaml

Daniel Bohnhardt
Contributed by Daniel Bohnhardt in #64117

The lint:yaml command provides a github output format that displays the errors as annotations in GitHub pull requests. Symfony 8.2 adds a gitlab format that generates a report in the GitLab Code Quality format, so the errors are displayed in the diff of your merge requests:

1
2
3
4
5
6
7
8
# .gitlab-ci.yml
lint-yaml:
    script:
        - php bin/console lint:yaml config --format=gitlab > gl-code-quality.json
    artifacts:
        when: always
        reports:
            codequality: gl-code-quality.json

A Configurable Lock for Lockable Commands

Nicolas Grekas
Contributed by Nicolas Grekas in #66020

The LockableTrait is the simplest way to prevent running the same command more than once at the same time. However, the trait creates by default its own semaphore or flock store, which is shared by the whole machine. For example, parallel test workers or two copies of the same project on one server block each other, and the lock doesn't work across several servers.

In Symfony 8.2, if your application defines a lock resource called console, all the commands that use LockableTrait lock with it:

1
2
3
4
# config/packages/lock.yaml
framework:
    lock:
        console: '%env(LOCK_DSN)%'

This feature is opt-in. If you don't define that resource, nothing changes, even if your application defines other lock resources. Commands that set their own lock factory keep using it.

Filtering Console Logs by Channel

HypeMC
Contributed by HypeMC in #66699

When you increase the verbosity of a command, the console handler of Monolog displays the logs of all the channels. If you only care about some of them (e.g. the SQL queries run by an import), you had to change the configuration of the handler. Symfony 8.2 adds the SYMFONY_CONSOLE_LOG_CHANNELS env var to select the channels when running the command:

1
2
3
4
5
6
7
8
# display only the logs of the "doctrine" channel
$ SYMFONY_CONSOLE_LOG_CHANNELS=doctrine php bin/console app:import -vvv

# display only the logs of these two channels
$ SYMFONY_CONSOLE_LOG_CHANNELS=doctrine,messenger php bin/console app:import -vvv

# display all logs except those of these two channels
$ SYMFONY_CONSOLE_LOG_CHANNELS='!event,!php' php bin/console app:import -vvv

Shell Completion of Paths

Nicolas Grekas
Contributed by Nicolas Grekas in #67258

When you install the shell completion script of a Symfony application, your shell stops completing file and directory paths for its commands, even for the arguments that expect a file. Symfony 8.2 allows commands to ask the shell to complete paths for any of their arguments and options:

1
2
3
4
5
6
7
8
9
10
11
use Symfony\Component\Console\Completion\CompletionInput;
use Symfony\Component\Console\Completion\CompletionSuggestions;

public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void
{
    if ($input->mustSuggestArgumentValuesFor('backup-dir')) {
        // completes only directories; use suggestPaths() to
        // complete both files and directories
        $suggestions->suggestDirectories();
    }
}

In invokable commands, the closures of the suggestedValues option now receive the CompletionSuggestions object as their second argument, so they can call these methods too. Arguments and options typed as InputFile complete paths without any code.

Note

Path completion requires a new version of the completion script. Run the completion command again to update the script installed in your shell.

Dropping Multiple Files

Robin Chalas
Contributed by Robin Chalas in #65616

Symfony 8.1 introduced the InputFile type, which lets you answer a question by pasting an image or dragging a file into the terminal. In Symfony 8.2, commands can receive several files at once. Use a variadic parameter or an array narrowed with PHPDoc:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// src/Command/ImportInvoicesCommand.php
use Symfony\Component\Console\Attribute\Argument;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Attribute\Ask;
use Symfony\Component\Console\Input\File\InputFile;

#[AsCommand('app:invoices:import')]
class ImportInvoicesCommand
{
    public function __invoke(
        #[Argument, Ask('Drop the invoices to import:')]
        InputFile ...$invoices,
    ): int {
        foreach ($invoices as $invoice) {
            // ...
        }

        // ...
    }
}

A single drag and drop can carry many files, and you can keep adding more files until you submit an empty line. The array syntax (@param InputFile[] $invoices) is the one to use in the properties of #[MapInput] classes, which can't be variadic.

If you prefer to ask the question yourself, use the new askFiles() method of SymfonyStyle:

1
$invoices = $io->askFiles('Drop the invoices to import:');
Published in #Living on the edge