danilovl/symfony-console-input-validation

Provide a simple method for adding input validation to Symfony console commands.

v0.1.4 2024-11-24 22:03 UTC

This package is auto-updated.

Last update: 2024-12-24 22:18:55 UTC


README

phpunit downloads latest Stable Version license

Symfony console input validation

About

Provide a simple method for adding input validation to Symfony console commands.

Requirements

  • PHP 8.3 or higher
  • Symfony 7.0 or higher

1. Installation

Install danilovl/symfony-console-input-validation package by Composer:

composer require danilovl/symfony-console-input-validation

2. Configuration

Change symfony Application in bin/console.

return function (array $context): Application {
    $kernel = new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);

    return new \Danilovl\SymfonyConsoleInputValidation\Console\Application($kernel);
};

2. Usage

Add InputOption, InputArgumnet using $this->getDefinition() in configure function.

When you call $input->getOption, $input->getArgument will be called validation callback.

<?php declare(strict_types=1);

namespace App\Application\Command;

use Danilovl\SymfonyConsoleInputValidation\Console\Input\InputOption as InputOptionValidation;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Exception\InvalidOptionException;
use Symfony\Component\Console\Input\{
    InputOption,
    InputInterface
};
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(name: 'app:command-test')]
class TestCommand extends Command
{
    protected function configure(): void
    {
        $validation = static function (mixed $value): void {
            if (empty($value)) {
                return;
            }

            if (!in_array($value, ['encrypt', 'decrypt'])) {
                throw new InvalidOptionException(sprintf('"%s" is not a valid type.', $value));
            }
        };

        $inputOption = new InputOptionValidation(
            name: 'type',
            mode: InputOption::VALUE_REQUIRED,
            description: 'Encryption type.',
            suggestedValues: ['encrypt', 'decrypt'],
            validation: $validation
        );

        $this->getDefinition()->addOption($inputOption);
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $input->getOption('type');

        return Command::SUCCESS;
    }
}

License

The symfony-console-input-validation package is open-sourced software licensed under the MIT license.