Validators for Form Fields
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
class FormValidator
|
||||
{
|
||||
/*
|
||||
* Private members
|
||||
*/
|
||||
|
||||
private array $fields;
|
||||
|
||||
/*
|
||||
* Constructor
|
||||
*/
|
||||
|
||||
public function __construct(FieldValidator ...$fields)
|
||||
{
|
||||
$this->fields = $fields;
|
||||
}
|
||||
|
||||
/*
|
||||
* Fluent Style
|
||||
*/
|
||||
|
||||
public static function create(FieldValidator ...$fields)
|
||||
{
|
||||
return new FormValidator(...$fields);
|
||||
}
|
||||
|
||||
/*
|
||||
* Methods
|
||||
*/
|
||||
|
||||
public function isValid()
|
||||
{
|
||||
foreach ($this->fields as $field) {
|
||||
if (!$field->isValid) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function getErrors()
|
||||
{
|
||||
$errors = [];
|
||||
|
||||
foreach ($this->fields as $field) {
|
||||
if (!$field->isValid()) array_push($errors, $field->getError());
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
public function getField(string $name)
|
||||
{
|
||||
$field = current(array_filter($this->fields, fn ($field) => strcmp($field->getName(), $name) === 0));
|
||||
if ($field !== false) {
|
||||
return $field;
|
||||
}
|
||||
|
||||
return "No field named $name";
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user