[Yaml] Improve YAML boolean escaping

- Moves dumping single-quoting logic into Yaml\Escaper
- Ensures that PHP values which would be interpreted as booleans in
  older versions of the YAML spec are escaped with single quotes when
  dumped by the Dumper.
This commit is contained in:
Peter Thompson 2015-01-05 11:24:54 +01:00
parent b4c1e898c0
commit 3760e67cb2
3 changed files with 42 additions and 4 deletions

View File

@ -72,7 +72,7 @@ class Escaper
*/
public static function requiresSingleQuoting($value)
{
return preg_match('/[ \s \' " \: \{ \} \[ \] , & \* \# \?] | \A[ \- ? | < > = ! % @ ` ]/x', $value);
return self::containsCharRequiresSingleQuoting($value) || self::isValueRequiresSingleQuoting($value);
}
/**
@ -86,4 +86,28 @@ class Escaper
{
return sprintf("'%s'", str_replace('\'', '\'\'', $value));
}
/**
* Determines if a PHP value contains any single characters that would cause
* the value to require single quoting in YAML.
*
* @param string $value A PHP value
* @return bool True if the value would require single quotes.
*/
private static function containsCharRequiresSingleQuoting($value)
{
return preg_match('/[ \s \' " \: \{ \} \[ \] , & \* \# \?] | \A[ \- ? | < > = ! % @ ` ]/x', $value);
}
/**
* Determines if a PHP value is entirely composed of a value that would
* require require single quoting in YAML.
*
* @param string $value A PHP value
* @return bool True if the value would require single quotes.
*/
private static function isValueRequiresSingleQuoting($value)
{
return in_array(strtolower($value), array('null', '~', 'true', 'false', 'y', 'n', 'yes', 'no', 'on', 'off'));
}
}

View File

@ -135,12 +135,10 @@ class Inline
case Escaper::requiresDoubleQuoting($value):
return Escaper::escapeWithDoubleQuotes($value);
case Escaper::requiresSingleQuoting($value):
case preg_match(self::getTimestampRegex(), $value):
return Escaper::escapeWithSingleQuotes($value);
case '' == $value:
return "''";
case preg_match(self::getTimestampRegex(), $value):
case in_array(strtolower($value), array('null', '~', 'true', 'false')):
return "'$value'";
default:
return $value;
}

View File

@ -190,6 +190,14 @@ class InlineTest extends \PHPUnit_Framework_TestCase
"'#cfcfcf'" => '#cfcfcf',
'::form_base.html.twig' => '::form_base.html.twig',
// Pre-YAML-1.2 booleans
"'y'" => 'y',
"'n'" => 'n',
"'yes'" => 'yes',
"'no'" => 'no',
"'on'" => 'on',
"'off'" => 'off',
'2007-10-30' => mktime(0, 0, 0, 10, 30, 2007),
'2007-10-30T02:59:43Z' => gmmktime(2, 59, 43, 10, 30, 2007),
'2007-10-30 02:59:43 Z' => gmmktime(2, 59, 43, 10, 30, 2007),
@ -257,6 +265,14 @@ class InlineTest extends \PHPUnit_Framework_TestCase
"'-dash'" => '-dash',
"'-'" => '-',
// Pre-YAML-1.2 booleans
"'y'" => 'y',
"'n'" => 'n',
"'yes'" => 'yes',
"'no'" => 'no',
"'on'" => 'on',
"'off'" => 'off',
// sequences
'[foo, bar, false, null, 12]' => array('foo', 'bar', false, null, 12),
'[\'foo,bar\', \'foo bar\']' => array('foo,bar', 'foo bar'),