You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
84 lines
2.4 KiB
PHP
84 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace jrosset\CliProgram\Validation\Validators;
|
|
|
|
use DateTimeImmutable;
|
|
use DateTimeInterface;
|
|
|
|
/**
|
|
* An argument/option value validator expecting a date and time
|
|
*
|
|
* @template-implements BasedValidator<RegexValidator>
|
|
*/
|
|
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 */ '/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})(?: (?<hour>\d{2}):(?<minute>\d{2})(?::(?<second>\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;
|
|
}
|
|
} |