<?php

namespace Planaday\Utility\FormBuilder\DataTypes;

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

/**
 * @implements DataType<float>
 */
class FloatType implements DataType{
	use TypeValidation;

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

		return $value;
	}

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