feat: add Type::ENUM as type constraint

This commit is contained in:
Victor Westerlund 2023-11-29 08:56:14 +01:00
parent 47987b9d97
commit f0377726d5
2 changed files with 24 additions and 6 deletions

View file

@ -10,12 +10,13 @@
enum Type { enum Type {
use xEnum; use xEnum;
case NULL;
case ENUM;
case ARRAY;
case NUMBER; case NUMBER;
case STRING; case STRING;
case BOOLEAN;
case ARRAY;
case OBJECT; case OBJECT;
case NULL; case BOOLEAN;
} }
class Rules { class Rules {
@ -28,6 +29,8 @@
// Typed array of type ReflectRules\Type // Typed array of type ReflectRules\Type
public ?array $types = null; public ?array $types = null;
public ?array $enum = null;
private bool $default_enabled = false; private bool $default_enabled = false;
public mixed $default; public mixed $default;
@ -72,8 +75,12 @@
return $this; return $this;
} }
// Set property Types // Add Type constraint with optional argument
public function type(Type $type): self { public function type(Type $type, mixed $arg = null): self {
if ($type === Type::ENUM) {
$this->enum = $arg;
}
$this->types[] = $type; $this->types[] = $type;
return $this; return $this;
} }
@ -121,6 +128,10 @@
return is_bool($value); return is_bool($value);
} }
private function eval_type_enum(mixed $value): bool {
return in_array($value, $this->enum);
}
/* /*
## Public eval methods ## Public eval methods
These are the entry-point eval methods that in turn can call other These are the entry-point eval methods that in turn can call other
@ -152,6 +163,7 @@
Type::BOOLEAN => $match = $this->eval_type_boolean($value, $scope), Type::BOOLEAN => $match = $this->eval_type_boolean($value, $scope),
Type::ARRAY, Type::ARRAY,
Type::OBJECT => $match = is_array($value), Type::OBJECT => $match = is_array($value),
Type::ENUM => $match = $this->eval_type_enum($value),
Type::NULL => $match = is_null($value) Type::NULL => $match = is_null($value)
}; };

View file

@ -84,7 +84,13 @@
// List names of each allowed type // List names of each allowed type
$types = implode(" or ", array_map(fn($type): string => $type->name, $rules->types)); $types = implode(" or ", array_map(fn($type): string => $type->name, $rules->types));
$this->add_error($name, "Value must be of type {$types}"); // List allowed enum values
if ($rules->enum) {
$values = implode(" or ", array_map(fn($value): string => "'{$value}'", $rules->enum));
$this->add_error($name, "Value must be exactly: {$values}");
}
$this->add_error($name, "Value must be of type {$types}{$enum_values}");
} }
if ($rules->min && !$rules->eval_min($value, $scope)) { if ($rules->min && !$rules->eval_min($value, $scope)) {