From ee2e611d6dca5317366ed5d697f2ef50344964dc Mon Sep 17 00:00:00 2001 From: Sukhwinder Dhillon Date: Mon, 4 Oct 2021 12:27:20 +0200 Subject: [PATCH 1/2] Introduce class `DateTimeValidator` --- src/DateTimeValidator.php | 65 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 src/DateTimeValidator.php diff --git a/src/DateTimeValidator.php b/src/DateTimeValidator.php new file mode 100644 index 0000000..1e35d61 --- /dev/null +++ b/src/DateTimeValidator.php @@ -0,0 +1,65 @@ +local = (bool) $local; + } + + /** + * Check whether the given date time is valid + * + * @param string|DateTime $value + * + * @return bool + */ + public function isValid($value) + { + // Multiple isValid() calls must not stack validation messages + $this->clearMessages(); + + if (! $value instanceof DateTime && ! is_string($value)) { + $this->addMessage($this->translate('Invalid date/time given.')); + + return false; + } + + if (! $value instanceof DateTime) { + $format = $this->local === true ? static::FORMAT : DateTime::RFC3339; + $dateTime = DateTime::createFromFormat($format, $value); + + if ($dateTime === false || $dateTime->format($format) !== $value) { + $this->addMessage(sprintf( + $this->translate("Date/time string not in the expected format: %s"), + $format + )); + + return false; + } + } + + return true; + } +} From 05230ab66d71b3732d99a53526d656de82b0f8d4 Mon Sep 17 00:00:00 2001 From: Sukhwinder Dhillon Date: Thu, 7 Oct 2021 10:55:35 +0200 Subject: [PATCH 2/2] Add `DateTimeValidationTest` class --- tests/DateTimeValidatorTest.php | 36 +++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 tests/DateTimeValidatorTest.php diff --git a/tests/DateTimeValidatorTest.php b/tests/DateTimeValidatorTest.php new file mode 100644 index 0000000..223b99a --- /dev/null +++ b/tests/DateTimeValidatorTest.php @@ -0,0 +1,36 @@ +assertTrue((new DateTimeValidator())->isValid(new DateTime()), 'current date is a valid date'); + } + + public function testDateTimeValidatorWithFalseAsDateTimeValue() + { + StaticTranslator::$instance = new NoopTranslator(); + $validator = new DateTimeValidator(); + + $this->assertFalse($validator->isValid(false), 'false is not a valid date'); + } + + public function testDateTimeValidatorWithStringAsDateTimeValue() + { + StaticTranslator::$instance = new NoopTranslator(); + $validator = new DateTimeValidator(); + + $this->assertTrue($validator->isValid('2021-02-15T15:03:01'), '15th Feb is a valid date'); + $this->assertFalse($validator->isValid('2021-02-31T15:03:01'), '31st Feb is not a valid date'); + $this->assertFalse($validator->isValid('2021-02-03T26:03:01'), "26 o'clock is not a valid time"); + $this->assertFalse($validator->isValid(''), 'Empty value is not a valid date'); + } +}