Add EnumValidator

2.x
Julien Rosset 2 years ago
parent 6b77ed1c42
commit cf547dee95

@ -0,0 +1,62 @@
<?php
namespace jrosset\CliProgram\Validation\Validators;
use jrosset\Collections\Collection;
use ReflectionEnum;
use ReflectionException;
use UnitEnum;
/**
* An argument/option value validator based on an enumeration
*
* @template TEnum of UnitEnum
* @template-implements IValidator<TEnum>
* @template-implements TInternalValueValidator<TEnum>
*/
class EnumValidator extends BasedValidator {
/**
* @var ReflectionEnum The enumeration
*/
private ReflectionEnum $enum;
/**
* Create a validator
*
* @param class-string<UnitEnum> $enumClass The enumeration class
*
* @throws ReflectionException If the enumeration class doesn't exist
*/
public function __construct (string $enumClass) {
$this->enum = new ReflectionEnum($enumClass);
$enumCases = new Collection();
foreach ($this->enum->getCases() as $enumCase) {
$enumCases->add($enumCase->getName());
}
parent::__construct(new ListValidator($enumCases));
}
/**
* @inheritDoc
*
* @throws ReflectionException
*/
public function getValidDefault (mixed $default): string|bool|int|float|array {
if ($default instanceof UnitEnum) {
$default = $default->name;
}
return $default;
}
/**
* @inheritDoc
*
* @throws ReflectionException
*/
public function getValue (): UnitEnum {
$enumCase = $this->getInternalValidator()->getValue();
return $this->enum->getCase($enumCase)->getValue();
}
}

@ -4,7 +4,9 @@ namespace jrosset\Tests\Commands;
use jrosset\CliProgram\Monolog\ConsoleOutputWithMonolog;
use jrosset\CliProgram\Validation\CommandWithValidation;
use jrosset\CliProgram\Validation\Validators\EnumValidator;
use jrosset\CliProgram\Validation\Validators\IntegerValidator;
use jrosset\Tests\Lang;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
@ -30,7 +32,15 @@ class Hello extends CommandWithValidation {
parent::configure();
$this->addArgument(
'lang',
InputArgument::OPTIONAL,
'The lang',
Lang::English,
new EnumValidator(Lang::class)
);
$this->addOption(
'repeat',
'r',
InputArgument::OPTIONAL,
'The number of repeat',
1,
@ -43,10 +53,12 @@ class Hello extends CommandWithValidation {
*/
protected function execute (InputInterface $input, OutputInterface $output): int {
$output->writeln('Command : ' . __CLASS__, OutputInterface::VERBOSITY_DEBUG);
$repeat = $input->getArgument('repeat');
var_dump($repeat);
/** @var Lang $lang */
$lang = $input->getArgument('lang');
$repeat = $input->getOption('repeat');
for ($curr = 0; $curr < $repeat; $curr++) {
$output->writeln('Hello !');
$output->writeln($lang->value);
}
$output->writeln('FIN', ConsoleOutputWithMonolog::OPTION_SKIP_MONOLOG);
return Command::SUCCESS;

@ -0,0 +1,9 @@
<?php
namespace jrosset\Tests;
enum Lang: string {
case French = 'Bonjour';
case English = 'Good morning';
case American = 'Hello';
}
Loading…
Cancel
Save