<?php

namespace Planaday\Utility\FormBuilder\DataTypes;

use Planaday\Utility\FormBuilder\InvalidFormDataException;
use Planaday\Utility\FormBuilder\Validator;

/**
 * @template T
 */
trait TypeValidation {
	/** @var Validator[] */
	protected array $validators = [];

	public function addValidator(Validator ...$validator): static {
		$this->validators = array_merge( $this->validators, $validator );
		return $this;
	}

	/**
	 * @param T $value
	 *
	 * @return true|InvalidFormDataException
	 */
	public function validate($value): bool|InvalidFormDataException {
		$exception = new InvalidFormDataException();
		$shouldThrow = false;

		foreach ($this->validators as $validator) {
			$result = $validator->validate($value ?? null);
			if ( $result !== true ) {
				$exception->addError($validator->getName(), $result);
				$shouldThrow = true;
			}
		}

		if ($shouldThrow) return $exception;
		return true;
	}

}