Skip to content

Commit

Permalink
🐛 throw ParseException on invalid date
Browse files Browse the repository at this point in the history
  • Loading branch information
homersimpsons committed Aug 11, 2024
1 parent 81cad0c commit 62f96e1
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
9 changes: 7 additions & 2 deletions Inline.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
8 changes: 8 additions & 0 deletions Tests/InlineTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down

0 comments on commit 62f96e1

Please sign in to comment.