<?php

namespace Planaday\Utility\FormBuilder\Validators;

use Planaday\Utility\FormBuilder\Validator;
use Stringable;

class RegexValidator implements Validator {
	use BasicValidator;

	public function __construct(
		protected string $checkName,
		protected string $regex,
		protected string $errorMessage = 'Input did not match regex'
	) {}

	public function getName(): string {
		return $this->checkName;
	}

	public function runValidator( mixed $data ): bool|string {
		if ( $data === null ) {
			return true;
		}

		if (!(is_scalar($data) || $data instanceof Stringable)) {
			return 'Invalid data type. Expected string.';
		}

		if ( preg_match($this->regex, trim($data)) ){
			return true;
		}

		return $this->errorMessage;
	}

	/**
	 * @inheritDoc
	 */
	public function jsonSerialize(): array {
		return [
			"type" => 'regex',
			"checkName" => $this->checkName,
			"regex" => substr($this->regex, 1, -1),
			"errorMessage" => $this->errorMessage,
			"conditions" => $this->conditions
		];
	}
}