From f3cb7ff9a795708533888053911502e2cf12655a Mon Sep 17 00:00:00 2001 From: John Noel Date: Tue, 15 Dec 2015 19:54:32 +0000 Subject: [PATCH] Fix non-6 digit microsecond date time formats RFC3339 allows for second fractions to be any length, however PHP's date/time formatting ALWAYS prints them out as 6 digits. This means if a date-time is passed with a < 6 digit second fractional, the FormatConstraint::validateDateTime will fail as the formatted date will contain 6 digits. E.g. '2000-05-01T12:12:12.123Z' is passed as a date time and is valid. However after parsing, format() will produce '2000-05-01T12:12:12:12.123000Z'. Fixes issue #145. --- src/JsonSchema/Constraints/FormatConstraint.php | 14 +++++++++++++- tests/JsonSchema/Tests/Constraints/FormatTest.php | 3 ++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/JsonSchema/Constraints/FormatConstraint.php b/src/JsonSchema/Constraints/FormatConstraint.php index c00baad6..c7897538 100644 --- a/src/JsonSchema/Constraints/FormatConstraint.php +++ b/src/JsonSchema/Constraints/FormatConstraint.php @@ -130,7 +130,19 @@ protected function validateDateTime($datetime, $format) return false; } - return $datetime === $dt->format($format); + if ($datetime === $dt->format($format)) { + return true; + } + + // handles the case where a non-6 digit microsecond datetime is passed + // which will fail the above string comparison because the passed + // $datetime may be '2000-05-01T12:12:12.123Z' but format() will return + // '2000-05-01T12:12:12.123000Z' + if ((strpos('u', $format) !== -1) && (intval($dt->format('u')) > 0)) { + return true; + } + + return false; } protected function validateRegex($regex) diff --git a/tests/JsonSchema/Tests/Constraints/FormatTest.php b/tests/JsonSchema/Tests/Constraints/FormatTest.php index 30797237..eb47983d 100644 --- a/tests/JsonSchema/Tests/Constraints/FormatTest.php +++ b/tests/JsonSchema/Tests/Constraints/FormatTest.php @@ -17,7 +17,7 @@ public function setUp() { date_default_timezone_set('UTC'); } - + public function testNullThing() { $validator = new FormatConstraint(); @@ -80,6 +80,7 @@ public function getValidFormats() array('2000-05-01T12:12:12+0100', 'date-time'), array('2000-05-01T12:12:12+01:00', 'date-time'), array('2000-05-01T12:12:12.123456Z', 'date-time'), + array('2000-05-01T12:12:12.123Z', 'date-time'), array('0', 'utc-millisec'),