From 62f96e1cfd4cf518882a36bfedcf1fe4093c1299 Mon Sep 17 00:00:00 2001 From: Guillaume Date: Sun, 11 Aug 2024 18:55:29 +0200 Subject: [PATCH] :bug: throw ParseException on invalid date --- Inline.php | 9 +++++++-- Tests/InlineTest.php | 8 ++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/Inline.php b/Inline.php index 36cc404a..94d3a5cd 100644 --- a/Inline.php +++ b/Inline.php @@ -700,8 +700,13 @@ private static function evaluateScalar(string $scalar, int $flags, array &$refer case Parser::preg_match('/^(-|\+)?[0-9][0-9_]*(\.[0-9_]+)?$/', $scalar): return (float) str_replace('_', '', $scalar); case Parser::preg_match(self::getTimestampRegex(), $scalar): - // When no timezone is provided in the parsed date, YAML spec says we must assume UTC. - $time = new \DateTime($scalar, new \DateTimeZone('UTC')); + try { + // When no timezone is provided in the parsed date, YAML spec says we must assume UTC. + $time = new \DateTime($scalar, new \DateTimeZone('UTC')); + } catch (\Exception $e) { + // Some dates accepted by the regex are not valid dates. + throw new ParseException(\sprintf('The date "%s" could not be parsed as it is an invalid date.', $scalar), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename, $e); + } if (Yaml::PARSE_DATETIME & $flags) { return $time; diff --git a/Tests/InlineTest.php b/Tests/InlineTest.php index d6e02fad..4e8d324a 100644 --- a/Tests/InlineTest.php +++ b/Tests/InlineTest.php @@ -579,6 +579,14 @@ public function testParseNestedTimestampListAsDateTimeObject(string $yaml, int $ $this->assertEquals($expectedNested, Inline::parse($yamlNested, Yaml::PARSE_DATETIME)); } + public function testParseInvalidDate() + { + $this->expectException(ParseException::class); + $this->expectExceptionMessageMatches('/^The date "2024-50-50" could not be parsed as it is an invalid date.*/'); + + Inline::parse('2024-50-50', Yaml::PARSE_DATETIME); + } + /** * @dataProvider getDateTimeDumpTests */