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.
PhpCliProgram/src/CliProgram/Validation/Validators/DateValidator.php

81 lines
2.1 KiB
PHP

<?php
namespace jrosset\CliProgram\Validation\Validators;
use DateTimeImmutable;
use DateTimeInterface;
/**
* An argument/option value validator expecting a date (without time)
*
* @template-implements BasedValidator<RegexValidator>
*/
class DateValidator extends AbstractDateTimeValidator {
/**
* @var DateTimeInterface The time part
*/
private DateTimeInterface $timePart;
/**
* Create a validator
*
* @param DateTimeInterface|null $timePart The time part
*/
public function __construct (?DateTimeInterface $timePart = null) {
$this->setTimePart($timePart ?? (new DateTimeImmutable())->setTimestamp(0));
parent::__construct();
}
/**
* @inheritDoc
*/
public function getValidDefault ($default) {
if ($default instanceof DateTimeInterface) {
return $default->format('Y-m-d');
}
return $default;
}
/**
* @inheritDoc
*/
protected function getPattern (): string {
return /** @lang PhpRegExp */ '/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/';
}
/**
* @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->getTimePart()->format('%H'),
(int)$this->getTimePart()->format('%i'),
(int)$this->getTimePart()->format('%s'),
);
}
/**
* The time part
*
* @return DateTimeInterface The time part
*/
public function getTimePart (): DateTimeInterface {
return $this->timePart;
}
/**
* Set the time part
*
* @param DateTimeInterface $timePart The time part
*
* @return $this
*/
public function setTimePart (DateTimeInterface $timePart): self {
$this->timePart = $timePart;
return $this;
}
}