62 lines
955 B
PHP
62 lines
955 B
PHP
<?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";
|
|
}
|
|
}
|