<?php

namespace Planaday\Utility\FormBuilder\DataTypes;

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

/**
 * @implements DataType<string>
 */
class StringType implements DataType{
	use TypeValidation;

	public function sanitize( mixed $value ): ?string {
		if ( $value !== null) {
			$castableToString =
				!is_resource($value) &&
				( !is_object($value) || method_exists($value, '__toString')) &&
				!is_array($value);

			if ( !$castableToString ) {
				throw (new InvalidFormDataException())->addError('DataError', 'Invalid data type. Expected string.');
			}

			$value = (string) $value;
		}

		return $value;
	}

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