Skip to content

[Yaml] support to parse and dump DateTime objects #17836

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 18, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/Symfony/Component/Yaml/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ CHANGELOG
3.1.0
-----

* Added support for parsing timestamps as `\DateTime` objects:

```php
Yaml::parse('2001-12-15 21:59:43.10 -5', Yaml::PARSE_DATETIME);
```

* `\DateTime` and `\DateTimeImmutable` objects are dumped as YAML timestamps.

* Deprecated usage of `%` at the beginning of an unquoted string.

* Added support for customizing the YAML parser behavior through an optional bit field:
Expand Down
44 changes: 27 additions & 17 deletions src/Symfony/Component/Yaml/Inline.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,15 +92,15 @@ public static function parse($value, $flags = 0, $references = array())
$i = 0;
switch ($value[0]) {
case '[':
$result = self::parseSequence($value, $i, $references);
$result = self::parseSequence($value, $flags, $i, $references);
++$i;
break;
case '{':
$result = self::parseMapping($value, $i, $references);
$result = self::parseMapping($value, $flags, $i, $references);
++$i;
break;
default:
$result = self::parseScalar($value, null, array('"', "'"), $i, true, $references);
$result = self::parseScalar($value, $flags, null, array('"', "'"), $i, true, $references);
}

// some comments are allowed at the end
Expand Down Expand Up @@ -152,6 +152,8 @@ public static function dump($value, $flags = 0)
}

return 'null';
case $value instanceof \DateTimeInterface:
return $value->format('c');
case is_object($value):
if (Yaml::DUMP_OBJECT & $flags) {
return '!php/object:'.serialize($value);
Expand Down Expand Up @@ -243,6 +245,7 @@ private static function dumpArray($value, $flags)
* Parses a scalar to a YAML string.
*
* @param string $scalar
* @param int $flags
* @param string $delimiters
* @param array $stringDelimiters
* @param int &$i
Expand All @@ -255,7 +258,7 @@ private static function dumpArray($value, $flags)
*
* @internal
*/
public static function parseScalar($scalar, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true, $references = array())
public static function parseScalar($scalar, $flags = 0, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true, $references = array())
{
if (in_array($scalar[$i], $stringDelimiters)) {
// quoted scalar
Expand Down Expand Up @@ -294,7 +297,7 @@ public static function parseScalar($scalar, $delimiters = null, $stringDelimiter
}

if ($evaluate) {
$output = self::evaluateScalar($output, $references);
$output = self::evaluateScalar($output, $flags, $references);
}
}

Expand Down Expand Up @@ -335,14 +338,15 @@ private static function parseQuotedScalar($scalar, &$i)
* Parses a sequence to a YAML string.
*
* @param string $sequence
* @param int $flags
* @param int &$i
* @param array $references
*
* @return string A YAML string
*
* @throws ParseException When malformed inline YAML string is parsed
*/
private static function parseSequence($sequence, &$i = 0, $references = array())
private static function parseSequence($sequence, $flags, &$i = 0, $references = array())
{
$output = array();
$len = strlen($sequence);
Expand All @@ -353,11 +357,11 @@ private static function parseSequence($sequence, &$i = 0, $references = array())
switch ($sequence[$i]) {
case '[':
// nested sequence
$output[] = self::parseSequence($sequence, $i, $references);
$output[] = self::parseSequence($sequence, $flags, $i, $references);
break;
case '{':
// nested mapping
$output[] = self::parseMapping($sequence, $i, $references);
$output[] = self::parseMapping($sequence, $flags, $i, $references);
break;
case ']':
return $output;
Expand All @@ -366,14 +370,14 @@ private static function parseSequence($sequence, &$i = 0, $references = array())
break;
default:
$isQuoted = in_array($sequence[$i], array('"', "'"));
$value = self::parseScalar($sequence, array(',', ']'), array('"', "'"), $i, true, $references);
$value = self::parseScalar($sequence, $flags, array(',', ']'), array('"', "'"), $i, true, $references);

// the value can be an array if a reference has been resolved to an array var
if (!is_array($value) && !$isQuoted && false !== strpos($value, ': ')) {
// embedded mapping?
try {
$pos = 0;
$value = self::parseMapping('{'.$value.'}', $pos, $references);
$value = self::parseMapping('{'.$value.'}', $flags, $pos, $references);
} catch (\InvalidArgumentException $e) {
// no, it's not
}
Expand All @@ -394,14 +398,15 @@ private static function parseSequence($sequence, &$i = 0, $references = array())
* Parses a mapping to a YAML string.
*
* @param string $mapping
* @param int $flags
* @param int &$i
* @param array $references
*
* @return string A YAML string
*
* @throws ParseException When malformed inline YAML string is parsed
*/
private static function parseMapping($mapping, &$i = 0, $references = array())
private static function parseMapping($mapping, $flags, &$i = 0, $references = array())
{
$output = array();
$len = strlen($mapping);
Expand All @@ -423,7 +428,7 @@ private static function parseMapping($mapping, &$i = 0, $references = array())
}

// key
$key = self::parseScalar($mapping, array(':', ' '), array('"', "'"), $i, false);
$key = self::parseScalar($mapping, $flags, array(':', ' '), array('"', "'"), $i, false);

// value
$done = false;
Expand All @@ -432,7 +437,7 @@ private static function parseMapping($mapping, &$i = 0, $references = array())
switch ($mapping[$i]) {
case '[':
// nested sequence
$value = self::parseSequence($mapping, $i, $references);
$value = self::parseSequence($mapping, $flags, $i, $references);
// Spec: Keys MUST be unique; first one wins.
// Parser cannot abort this mapping earlier, since lines
// are processed sequentially.
Expand All @@ -443,7 +448,7 @@ private static function parseMapping($mapping, &$i = 0, $references = array())
break;
case '{':
// nested mapping
$value = self::parseMapping($mapping, $i, $references);
$value = self::parseMapping($mapping, $flags, $i, $references);
// Spec: Keys MUST be unique; first one wins.
// Parser cannot abort this mapping earlier, since lines
// are processed sequentially.
Expand All @@ -456,7 +461,7 @@ private static function parseMapping($mapping, &$i = 0, $references = array())
case ' ':
break;
default:
$value = self::parseScalar($mapping, array(',', '}'), array('"', "'"), $i, true, $references);
$value = self::parseScalar($mapping, $flags, array(',', '}'), array('"', "'"), $i, true, $references);
// Spec: Keys MUST be unique; first one wins.
// Parser cannot abort this mapping earlier, since lines
// are processed sequentially.
Expand All @@ -482,13 +487,14 @@ private static function parseMapping($mapping, &$i = 0, $references = array())
* Evaluates scalars and replaces magic values.
*
* @param string $scalar
* @param int $flags
* @param array $references
*
* @return string A YAML string
*
* @throws ParseException when object parsing support was disabled and the parser detected a PHP object or when a reference could not be resolved
*/
private static function evaluateScalar($scalar, $references = array())
private static function evaluateScalar($scalar, $flags, $references = array())
{
$scalar = trim($scalar);
$scalarLower = strtolower($scalar);
Expand Down Expand Up @@ -527,7 +533,7 @@ private static function evaluateScalar($scalar, $references = array())
case 0 === strpos($scalar, '!str'):
return (string) substr($scalar, 5);
case 0 === strpos($scalar, '! '):
return (int) self::parseScalar(substr($scalar, 2));
return (int) self::parseScalar(substr($scalar, 2), $flags);
case 0 === strpos($scalar, '!php/object:'):
if (self::$objectSupport) {
return unserialize(substr($scalar, 12));
Expand Down Expand Up @@ -573,6 +579,10 @@ private static function evaluateScalar($scalar, $references = array())
case preg_match('/^(-|\+)?[0-9,]+(\.[0-9]+)?$/', $scalar):
return (float) str_replace(',', '', $scalar);
case preg_match(self::getTimestampRegex(), $scalar):
if (Yaml::PARSE_DATETIME & $flags) {
return new \DateTime($scalar,new \DateTimeZone('UTC'));
}

$timeZone = date_default_timezone_get();
date_default_timezone_set('UTC');
$time = strtotime($scalar);
Expand Down
53 changes: 52 additions & 1 deletion src/Symfony/Component/Yaml/Tests/InlineTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ public function getTestsForParseWithMapObjects()
array("'#cfcfcf'", '#cfcfcf'),
array('::form_base.html.twig', '::form_base.html.twig'),

array('2007-10-30', mktime(0, 0, 0, 10, 30, 2007)),
array('2007-10-30', gmmktime(0, 0, 0, 10, 30, 2007)),
array('2007-10-30T02:59:43Z', gmmktime(2, 59, 43, 10, 30, 2007)),
array('2007-10-30 02:59:43 Z', gmmktime(2, 59, 43, 10, 30, 2007)),
array('1960-10-30 02:59:43 Z', gmmktime(2, 59, 43, 10, 30, 1960)),
Expand Down Expand Up @@ -481,4 +481,55 @@ public function getTestsForDump()
array('[foo, \'@foo.baz\', { \'%foo%\': \'foo is %foo%\', bar: \'%foo%\' }, true, \'@service_container\']', array('foo', '@foo.baz', array('%foo%' => 'foo is %foo%', 'bar' => '%foo%'), true, '@service_container')),
);
}

/**
* @dataProvider getTimestampTests
*/
public function testParseTimestampAsUnixTimestampByDefault($yaml, $year, $month, $day, $hour, $minute, $second)
{
$this->assertSame(gmmktime($hour, $minute, $second, $month, $day, $year), Inline::parse($yaml));
}

/**
* @dataProvider getTimestampTests
*/
public function testParseTimestampAsDateTimeObject($yaml, $year, $month, $day, $hour, $minute, $second)
{
$expected = new \DateTime('now', new \DateTimeZone('UTC'));
$expected->setDate($year, $month, $day);
$expected->setTime($hour, $minute, $second);

$this->assertEquals($expected, Inline::parse($yaml, Yaml::PARSE_DATETIME));
}

public function getTimestampTests()
{
return array(
'canonical' => array('2001-12-15T02:59:43.1Z', 2001, 12, 15, 2, 59, 43),
'ISO-8601' => array('2001-12-15t21:59:43.10-05:00', 2001, 12, 16, 2, 59, 43),
'spaced' => array('2001-12-15 21:59:43.10 -5', 2001, 12, 16, 2, 59, 43),
'date' => array('2001-12-15', 2001, 12, 15, 0, 0, 0),
);
}

/**
* @dataProvider getDateTimeDumpTests
*/
public function testDumpDateTime($dateTime, $expected)
{
$this->assertSame($expected, Inline::dump($dateTime));
}

public function getDateTimeDumpTests()
{
$tests = array();

$dateTime = new \DateTime('2001-12-15 21:59:43', new \DateTimeZone('UTC'));
$tests['date-time-utc'] = array($dateTime, '2001-12-15T21:59:43+00:00');

$dateTime = new \DateTimeImmutable('2001-07-15 21:59:43', new \DateTimeZone('Europe/Berlin'));
$tests['immutable-date-time-europe-berlin'] = array($dateTime, '2001-07-15T21:59:43+02:00');

return $tests;
}
}
1 change: 1 addition & 0 deletions src/Symfony/Component/Yaml/Yaml.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class Yaml
const PARSE_OBJECT = 4;
const PARSE_OBJECT_FOR_MAP = 8;
const DUMP_EXCEPTION_ON_INVALID_TYPE = 16;
const PARSE_DATETIME = 32;

/**
* Parses YAML into a PHP value.
Expand Down