You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
1.9 KiB
PHP
75 lines
1.9 KiB
PHP
<?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();
|
|
}
|
|
} |