validator icon indicating copy to clipboard operation
validator copied to clipboard

Introduce ErrorsAware interface and a base trait implementation

Open xepozz opened this issue 3 years ago • 0 comments

ErrorsAwareInterface is a marker same as PostValidationHookInterface. It may set all errors after validation into an validated object. It may unify forms and request-model.

interface ErrorsAwareInterface {
  public function addError(string $attribute): void;
  public function getError(string $attribute): mixed; <-- either Stringable or Stringable[]
  public function hasError(string $attribute): bool;
  
  public function setErrors(array $errorsMap): void;
  public function getErrors(): array;
  public function hasErrors(): bool;
}

So the base trait should implement all of these methods;

Usage is simple:

$validator->validate($object);

if ($object->hasErrors()) {
  // ...
}

Instead of

$result = $validator->validate($object);

if ($result->hasErrors()) {
  // ...
}

It may be useful with nested structures that may be hard accessible and just a shortcut to pass both errors and the object somewhere together.

xepozz avatar Feb 01 '23 16:02 xepozz