*/ class DateTimeValidator extends AbstractDateTimeValidator { /** * @var bool Is the time part mandatory ? */ private bool $timeMandatory; /** * Create a validator * * @param bool $mandatoryDate Is the time part mandatory ? */ public function __construct (bool $mandatoryDate = false) { $this->setTimeMandatory($mandatoryDate); parent::__construct(); } /** * @inheritDoc */ public function getValidDefault (mixed $default): string|bool|int|float|array|null { if ($default instanceof DateTimeInterface) { return $default->format('Y-m-d H:i:s'); } return $default; } /** * @inheritDoc */ protected function getPattern (): string { /** @noinspection RegExpUnnecessaryNonCapturingGroup */ return /** @lang PhpRegExp */ '/^(?\d{4})-(?\d{2})-(?\d{2})(?: (?\d{2}):(?\d{2})(?::(?\d{2}))?)' . ($this->isTimeMandatory() ? '' : '?') . '$/'; } /** * @inheritDoc */ public function getValue (): DateTimeInterface { $value = new DateTimeImmutable(); $value = $value->setDate( (int)$this->getInternalValidator()->getMatch('year'), (int)$this->getInternalValidator()->getMatch('month'), (int)$this->getInternalValidator()->getMatch('day'), ); return $value->setTime( (int)($this->getInternalValidator()->getMatch('hour') ?? 0), (int)($this->getInternalValidator()->getMatch('minute') ?? 0), (int)($this->getInternalValidator()->getMatch('second') ?? 0), ); } /** * Is the time part mandatory ? * * @return bool Is the time part mandatory ? */ public function isTimeMandatory (): bool { return $this->timeMandatory; } /** * Is the time part mandatory ? * * @param bool $timeMandatory Is the time part mandatory ? * * @return $this */ public function setTimeMandatory (bool $timeMandatory): self { $this->timeMandatory = $timeMandatory; return $this; } }