<?php

namespace Planaday\Utility\FormBuilder\DataTypes;

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

/**
 * @implements DataType<int>
 */
class IntType implements DataType{
	use TypeValidation;

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

		return $value;
	}

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