<?php

namespace Planaday\Utility\FormBuilder\DataTypes;

use Planaday\Utility\FormBuilder\DataType;
use Planaday\Utility\FormBuilder\InvalidFormDataException;

/**
 * @implements DataType<bool>
 */
class BoolType implements DataType{
	use TypeValidation;

	public function sanitize( mixed $value ): ?bool {
		if ( $value !== null) {
			$value = filter_var($value, FILTER_VALIDATE_BOOL, FILTER_NULL_ON_FAILURE);
			if ( $value === null) {
				throw (new InvalidFormDataException())->addError('DataError', 'Invalid data type. Expected bool.');
			}
		}

		return $value;
	}

	public function jsonSerialize(): array {
		return [
			"type" => 'bool',
			"validators" => $this->validators
		];
	}
}