parent
ba27ae5963
commit
761067e48a
@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace jrosset\CliProgram\Validation\Validators;
|
||||
|
||||
use Arrayy\Type\StringCollection;
|
||||
use Closure;
|
||||
|
||||
/**
|
||||
* An argument/option value validator based on an associative list of value
|
||||
*
|
||||
* Key = User input
|
||||
* <br>Value = Real value (see {@see IValidator::getValue() getValue()})
|
||||
*
|
||||
* @implements IValidatorWithSuggestions<string>
|
||||
*/
|
||||
class AssociativeListValidator implements IValidatorWithSuggestions {
|
||||
use TIdenticalValidDefaultValidator;
|
||||
|
||||
/**
|
||||
* @use TInternalValueValidator<string>
|
||||
*/
|
||||
use TInternalValueValidator;
|
||||
|
||||
/**
|
||||
* @var StringCollection The list of allowed values
|
||||
*/
|
||||
private StringCollection $allowedValues;
|
||||
|
||||
/**
|
||||
* Create a validator
|
||||
*
|
||||
* @param StringCollection|null $allowedValues The list of allowed values
|
||||
*/
|
||||
public function __construct (?StringCollection $allowedValues = null) {
|
||||
$this->setAllowedValues($allowedValues ?? new StringCollection());
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function validate (mixed $value): bool {
|
||||
if ($this->allowedValues->keyExists($value)) {
|
||||
$this->setValue($this->allowedValues->get($value));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The list of allowed values
|
||||
*
|
||||
* @return StringCollection The list of allowed values
|
||||
*/
|
||||
public function getAllowedValues (): StringCollection {
|
||||
return $this->allowedValues;
|
||||
}
|
||||
/**
|
||||
* Set the list of allowed values
|
||||
*
|
||||
* @param StringCollection $allowedValues The list of allowed values
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function setAllowedValues (StringCollection $allowedValues): self {
|
||||
$this->allowedValues = $allowedValues;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getSuggestions (): Closure|array {
|
||||
return $this->getAllowedValues()->getKeys()->toArray();
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue