<?php

namespace Planaday\Utility\FormBuilder\Validators;

use Planaday\Utility\FormBuilder\Validator;

class Required implements Validator {
	use BasicValidator;

	protected bool $zeroIsInvalid = false;

	public function __construct(
		protected string $errorMessage = 'This field is required'
	) {}

	/**
	 * Both false and 0 are considered invalid
	 */
	public function zeroIsInvalid():self{
		$this->zeroIsInvalid = true;
		return $this;
	}

	public function getName(): string {
		return 'required';
	}

	public function runValidator( mixed $data ): bool|string {
		if (
			$data === null ||
			(is_string($data) && trim($data) === '') ||
			$data === [] ||
			($this->zeroIsInvalid && $data === false) ||
			($this->zeroIsInvalid && $data === 0)
		) {
			return $this->errorMessage;
		}

		return true;
	}

	public function jsonSerialize(): array {
		return [
			"type" => 'required',
			"checkName" => $this->getName(),
			"errorMessage" => $this->errorMessage,
			"conditions" => $this->conditions,
			"zeroIsInvalid" => $this->zeroIsInvalid
		];
	}
}