| 1 |
<?php |
| 2 |
|
| 3 |
namespace ipl\Validator; |
| 4 |
|
| 5 |
use DateTime; |
| 6 |
|
| 7 |
/** |
| 8 |
* Validate date-and-time input values |
| 9 |
*/ |
| 10 |
class DateTimeValidator extends BaseValidator |
| 11 |
{ |
| 12 |
/** @var string Default date time format */ |
| 13 |
public const FORMAT = 'Y-m-d\TH:i:s'; |
| 14 |
|
| 15 |
/** @var bool Whether to use the default date time format */ |
| 16 |
protected bool $local; |
| 17 |
|
| 18 |
/** |
| 19 |
* Create a new DateTimeValidator |
| 20 |
* |
| 21 |
* @param bool $local Whether to use the local date time format instead of RFC3339 |
| 22 |
*/ |
| 23 |
public function __construct(bool $local = true) |
| 24 |
{ |
| 25 |
$this->local = $local; |
| 26 |
} |
| 27 |
|
| 28 |
/** |
| 29 |
* Check whether the given date time is valid |
| 30 |
* |
| 31 |
* @param string|DateTime $value |
| 32 |
* |
| 33 |
* @return bool |
| 34 |
*/ |
| 35 |
public function isValid($value): bool |
| 36 |
{ |
| 37 |
// Reset messages from a previous isValid() call. |
| 38 |
$this->clearMessages(); |
| 39 |
|
| 40 |
if (! $value instanceof DateTime && ! is_string($value)) { |
| 41 |
$this->addMessage($this->translate('Invalid date/time given.')); |
| 42 |
|
| 43 |
return false; |
| 44 |
} |
| 45 |
|
| 46 |
if (! $value instanceof DateTime) { |
| 47 |
$format = $this->local === true ? static::FORMAT : DateTime::RFC3339; |
| 48 |
$dateTime = DateTime::createFromFormat($format, $value); |
| 49 |
|
| 50 |
if ($dateTime === false || $dateTime->format($format) !== $value) { |
| 51 |
$this->addMessage(sprintf( |
| 52 |
$this->translate("Date/time string not in the expected format: %s"), |
| 53 |
$format |
| 54 |
)); |
| 55 |
|
| 56 |
return false; |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
return true; |
| 61 |
} |
| 62 |
} |