danilovl / symfony-console-input-validation
Provide a simple method for adding input validation to Symfony console commands.
Installs: 14
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
Type:package
Requires
- php: ^8.3.0
- symfony/console: ^7.0
- symfony/framework-bundle: ^7.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.64
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^10.2
README
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.