From 95b21edd11e82c6446b1a7f381e342addab63e5d Mon Sep 17 00:00:00 2001 From: Christian Blank Date: Sun, 15 Jan 2017 07:32:29 +0100 Subject: [PATCH 1/2] Add datetime type --- spec/Type/DatetimeTypeSpec.php | 35 +++++++++++++++++ src/Type/DatetimeType.php | 69 ++++++++++++++++++++++++++++++++++ 2 files changed, 104 insertions(+) create mode 100644 spec/Type/DatetimeTypeSpec.php create mode 100644 src/Type/DatetimeType.php diff --git a/spec/Type/DatetimeTypeSpec.php b/spec/Type/DatetimeTypeSpec.php new file mode 100644 index 0000000..27ed724 --- /dev/null +++ b/spec/Type/DatetimeTypeSpec.php @@ -0,0 +1,35 @@ +beConstructedWith('d-m-Y h:m:s', 'UTC'); + $this->shouldHaveType(DatetimeType::class); + } + + function it_should_return_valid_for_correct_values() + { + $this->beConstructedWith('d-m-Y h:m:s', 'Europe/Berlin'); + + $this->check('12-12-2012 12:12:10')->isValid()->shouldBe(true); + } + + function it_should_return_invalid_for_others() + { + $this->beConstructedWith('d-m-Y h:m:s', 'Europe/Berlin'); + + $this->check(null)->isValid()->shouldBe(false); + $this->check('foo')->isValid()->shouldBe(false); + $this->check([])->isValid()->shouldBe(false); + $this->check(1.234)->isValid()->shouldBe(false); + $this->check(true)->isValid()->shouldBe(false); + $this->check(false)->isValid()->shouldBe(false); + } +} diff --git a/src/Type/DatetimeType.php b/src/Type/DatetimeType.php new file mode 100644 index 0000000..6271283 --- /dev/null +++ b/src/Type/DatetimeType.php @@ -0,0 +1,69 @@ +datetimeFormat = $format; + $this->datetimeZone = $datetimeZone; + } + + /** + * @param mixed $value + * + * @return ResultInterface + */ + public function check($value) + { + $checkResult = is_string($value) && $this->isValidDatetime($value); + + return new Result( + $checkResult, + !$checkResult ? [sprintf(self::$errorMessage, json_encode($value))] : [] + ); + } + + /** + * @param string $value + * + * @return bool + */ + private function isValidDatetime($value) { + $date = DateTime::createFromFormat($this->datetimeFormat, $value, new DateTimeZone($this->datetimeZone)); + $errors = DateTime::getLastErrors()["warning_count"]; + + return $date && $errors["warning_count"] == 0 && $errors["error_count"] == 0; + } +} From 496973b92eeab9c6577f382fba198873d37a6575 Mon Sep 17 00:00:00 2001 From: Christian Blank Date: Sun, 15 Jan 2017 07:34:23 +0100 Subject: [PATCH 2/2] Update type list in readme --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 1fed4bf..7a1b2b1 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,7 @@ Currently the following types are supported: * String * Object * List + * Datetime There are some open issues with ideas for more types. Feel free to send pull requests.