parent
caa254ab80
commit
0ef982f8b7
@ -1,62 +0,0 @@
|
||||
<?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();
|
||||
}
|
||||
}
|
@ -1,9 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace jrosset\Tests;
|
||||
|
||||
enum Lang: string {
|
||||
case French = 'Bonjour';
|
||||
case English = 'Good morning';
|
||||
case American = 'Hello';
|
||||
}
|
Loading…
Reference in New Issue