<?php

namespace Velis\Dto\Validators;

use Attribute;
use DateTime;
use Exception;

/**
 * Date format checking validator.
 * - 'c' format is a special case for ISO 8601 date format and every valid date will return true.
 * @author Szymon Janaczek <szymon.janaczek@velistech.com>
 */
#[Attribute]
class DateFormatValidator extends BaseValidator
{
    public function __construct(
        public string $dateFormat,
        public string $message = 'Invalid date format.',
        public bool $nullable = false
    ) {
    }

    /**
     * {@inheritDoc}
     */
    public function validate($value): bool
    {
        if (is_null($value) && $this->nullable) {
            return true;
        }

        try {
            $date = new DateTime($value);
        } catch (Exception) {
            return false;
        }

        return $date->format($this->dateFormat) === $value || $this->dateFormat === 'c';
    }
}
