4
* This file is part of the Symfony package.
6
* (c) Fabien Potencier <fabien@symfony.com>
8
* For the full copyright and license information, please view the LICENSE
9
* file that was distributed with this source code.
12
namespace Symfony\Component\Yaml;
14
use Symfony\Component\Yaml\Exception\ParseException;
15
use Symfony\Component\Yaml\Exception\DumpException;
18
* Inline implements a YAML parser/dumper for the YAML inline syntax.
20
* @author Fabien Potencier <fabien@symfony.com>
24
const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\']*(?:\'\'[^\']*)*)\')';
26
private static $exceptionOnInvalidType = false;
27
private static $objectSupport = false;
28
private static $objectForMap = false;
31
* Converts a YAML string to a PHP array.
33
* @param string $value A YAML string
34
* @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
35
* @param bool $objectSupport true if object support is enabled, false otherwise
36
* @param bool $objectForMap true if maps should return a stdClass instead of array()
37
* @param array $references Mapping of variable names to values
39
* @return array A PHP array representing the YAML string
41
* @throws ParseException
43
public static function parse($value, $exceptionOnInvalidType = false, $objectSupport = false, $objectForMap = false, $references = array())
45
self::$exceptionOnInvalidType = $exceptionOnInvalidType;
46
self::$objectSupport = $objectSupport;
47
self::$objectForMap = $objectForMap;
49
$value = trim($value);
51
if (0 == strlen($value)) {
55
if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) {
56
$mbEncoding = mb_internal_encoding();
57
mb_internal_encoding('ASCII');
63
$result = self::parseSequence($value, $i, $references);
67
$result = self::parseMapping($value, $i, $references);
71
$result = self::parseScalar($value, null, array('"', "'"), $i, true, $references);
74
// some comments are allowed at the end
75
if (preg_replace('/\s+#.*$/A', '', substr($value, $i))) {
76
throw new ParseException(sprintf('Unexpected characters near "%s".', substr($value, $i)));
79
if (isset($mbEncoding)) {
80
mb_internal_encoding($mbEncoding);
87
* Dumps a given PHP variable to a YAML string.
89
* @param mixed $value The PHP variable to convert
90
* @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
91
* @param bool $objectSupport true if object support is enabled, false otherwise
93
* @return string The YAML string representing the PHP array
95
* @throws DumpException When trying to dump PHP resource
97
public static function dump($value, $exceptionOnInvalidType = false, $objectSupport = false)
100
case is_resource($value):
101
if ($exceptionOnInvalidType) {
102
throw new DumpException(sprintf('Unable to dump PHP resources in a YAML file ("%s").', get_resource_type($value)));
106
case is_object($value):
107
if ($objectSupport) {
108
return '!!php/object:'.serialize($value);
111
if ($exceptionOnInvalidType) {
112
throw new DumpException('Object support when dumping a YAML file has been disabled.');
116
case is_array($value):
117
return self::dumpArray($value, $exceptionOnInvalidType, $objectSupport);
118
case null === $value:
120
case true === $value:
122
case false === $value:
124
case ctype_digit($value):
125
return is_string($value) ? "'$value'" : (int) $value;
126
case is_numeric($value):
127
$locale = setlocale(LC_NUMERIC, 0);
128
if (false !== $locale) {
129
setlocale(LC_NUMERIC, 'C');
131
if (is_float($value)) {
132
$repr = strval($value);
133
if (is_infinite($value)) {
134
$repr = str_ireplace('INF', '.Inf', $repr);
135
} elseif (floor($value) == $value && $repr == $value) {
136
// Preserve float data type since storing a whole number will result in integer value.
137
$repr = '!!float '.$repr;
140
$repr = is_string($value) ? "'$value'" : strval($value);
142
if (false !== $locale) {
143
setlocale(LC_NUMERIC, $locale);
149
case Escaper::requiresDoubleQuoting($value):
150
return Escaper::escapeWithDoubleQuotes($value);
151
case Escaper::requiresSingleQuoting($value):
152
case preg_match(self::getTimestampRegex(), $value):
153
return Escaper::escapeWithSingleQuotes($value);
160
* Dumps a PHP array to a YAML string.
162
* @param array $value The PHP array to dump
163
* @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
164
* @param bool $objectSupport true if object support is enabled, false otherwise
166
* @return string The YAML string representing the PHP array
168
private static function dumpArray($value, $exceptionOnInvalidType, $objectSupport)
171
$keys = array_keys($value);
172
if ((1 == count($keys) && '0' == $keys[0])
173
|| (count($keys) > 1 && array_reduce($keys, function ($v, $w) { return (int) $v + $w; }, 0) == count($keys) * (count($keys) - 1) / 2)
176
foreach ($value as $val) {
177
$output[] = self::dump($val, $exceptionOnInvalidType, $objectSupport);
180
return sprintf('[%s]', implode(', ', $output));
185
foreach ($value as $key => $val) {
186
$output[] = sprintf('%s: %s', self::dump($key, $exceptionOnInvalidType, $objectSupport), self::dump($val, $exceptionOnInvalidType, $objectSupport));
189
return sprintf('{ %s }', implode(', ', $output));
193
* Parses a scalar to a YAML string.
195
* @param string $scalar
196
* @param string $delimiters
197
* @param array $stringDelimiters
199
* @param bool $evaluate
200
* @param array $references
202
* @return string A YAML string
204
* @throws ParseException When malformed inline YAML string is parsed
206
public static function parseScalar($scalar, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true, $references = array())
208
if (in_array($scalar[$i], $stringDelimiters)) {
210
$output = self::parseQuotedScalar($scalar, $i);
212
if (null !== $delimiters) {
213
$tmp = ltrim(substr($scalar, $i), ' ');
214
if (!in_array($tmp[0], $delimiters)) {
215
throw new ParseException(sprintf('Unexpected characters (%s).', substr($scalar, $i)));
221
$output = substr($scalar, $i);
222
$i += strlen($output);
225
if (false !== $strpos = strpos($output, ' #')) {
226
$output = rtrim(substr($output, 0, $strpos));
228
} elseif (preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) {
230
$i += strlen($output);
232
throw new ParseException(sprintf('Malformed inline YAML string (%s).', $scalar));
236
$output = self::evaluateScalar($output, $references);
244
* Parses a quoted scalar to YAML.
246
* @param string $scalar
249
* @return string A YAML string
251
* @throws ParseException When malformed inline YAML string is parsed
253
private static function parseQuotedScalar($scalar, &$i)
255
if (!preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) {
256
throw new ParseException(sprintf('Malformed inline YAML string (%s).', substr($scalar, $i)));
259
$output = substr($match[0], 1, strlen($match[0]) - 2);
261
$unescaper = new Unescaper();
262
if ('"' == $scalar[$i]) {
263
$output = $unescaper->unescapeDoubleQuotedString($output);
265
$output = $unescaper->unescapeSingleQuotedString($output);
268
$i += strlen($match[0]);
274
* Parses a sequence to a YAML string.
276
* @param string $sequence
278
* @param array $references
280
* @return string A YAML string
282
* @throws ParseException When malformed inline YAML string is parsed
284
private static function parseSequence($sequence, &$i = 0, $references = array())
287
$len = strlen($sequence);
292
switch ($sequence[$i]) {
295
$output[] = self::parseSequence($sequence, $i, $references);
299
$output[] = self::parseMapping($sequence, $i, $references);
307
$isQuoted = in_array($sequence[$i], array('"', "'"));
308
$value = self::parseScalar($sequence, array(',', ']'), array('"', "'"), $i, true, $references);
310
// the value can be an array if a reference has been resolved to an array var
311
if (!is_array($value) && !$isQuoted && false !== strpos($value, ': ')) {
315
$value = self::parseMapping('{'.$value.'}', $pos, $references);
316
} catch (\InvalidArgumentException $e) {
329
throw new ParseException(sprintf('Malformed inline YAML string %s', $sequence));
333
* Parses a mapping to a YAML string.
335
* @param string $mapping
337
* @param array $references
339
* @return string A YAML string
341
* @throws ParseException When malformed inline YAML string is parsed
343
private static function parseMapping($mapping, &$i = 0, $references = array())
346
$len = strlen($mapping);
349
// {foo: bar, bar:foo, ...}
351
switch ($mapping[$i]) {
357
if (self::$objectForMap) {
358
return (object) $output;
365
$key = self::parseScalar($mapping, array(':', ' '), array('"', "'"), $i, false);
371
switch ($mapping[$i]) {
374
$value = self::parseSequence($mapping, $i, $references);
375
// Spec: Keys MUST be unique; first one wins.
376
// Parser cannot abort this mapping earlier, since lines
377
// are processed sequentially.
378
if (!isset($output[$key])) {
379
$output[$key] = $value;
385
$value = self::parseMapping($mapping, $i, $references);
386
// Spec: Keys MUST be unique; first one wins.
387
// Parser cannot abort this mapping earlier, since lines
388
// are processed sequentially.
389
if (!isset($output[$key])) {
390
$output[$key] = $value;
398
$value = self::parseScalar($mapping, array(',', '}'), array('"', "'"), $i, true, $references);
399
// Spec: Keys MUST be unique; first one wins.
400
// Parser cannot abort this mapping earlier, since lines
401
// are processed sequentially.
402
if (!isset($output[$key])) {
403
$output[$key] = $value;
417
throw new ParseException(sprintf('Malformed inline YAML string %s', $mapping));
421
* Evaluates scalars and replaces magic values.
423
* @param string $scalar
424
* @param array $references
426
* @return string A YAML string
428
* @throws ParseException when object parsing support was disabled and the parser detected a PHP object or when a reference could not be resolved
430
private static function evaluateScalar($scalar, $references = array())
432
$scalar = trim($scalar);
433
$scalarLower = strtolower($scalar);
435
if (0 === strpos($scalar, '*')) {
436
if (false !== $pos = strpos($scalar, '#')) {
437
$value = substr($scalar, 1, $pos - 2);
439
$value = substr($scalar, 1);
443
if (false === $value || '' === $value) {
444
throw new ParseException('A reference must contain at least one character.');
447
if (!array_key_exists($value, $references)) {
448
throw new ParseException(sprintf('Reference "%s" does not exist.', $value));
451
return $references[$value];
455
case 'null' === $scalarLower:
457
case '~' === $scalar:
459
case 'true' === $scalarLower:
461
case 'false' === $scalarLower:
463
// Optimise for returning strings.
464
case $scalar[0] === '+' || $scalar[0] === '-' || $scalar[0] === '.' || $scalar[0] === '!' || is_numeric($scalar[0]):
466
case 0 === strpos($scalar, '!str'):
467
return (string) substr($scalar, 5);
468
case 0 === strpos($scalar, '! '):
469
return intval(self::parseScalar(substr($scalar, 2)));
470
case 0 === strpos($scalar, '!!php/object:'):
471
if (self::$objectSupport) {
472
return unserialize(substr($scalar, 13));
475
if (self::$exceptionOnInvalidType) {
476
throw new ParseException('Object support when parsing a YAML file has been disabled.');
480
case 0 === strpos($scalar, '!!float '):
481
return (float) substr($scalar, 8);
482
case ctype_digit($scalar):
484
$cast = intval($scalar);
486
return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw);
487
case '-' === $scalar[0] && ctype_digit(substr($scalar, 1)):
489
$cast = intval($scalar);
491
return '0' == $scalar[1] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw);
492
case is_numeric($scalar):
493
return '0x' == $scalar[0].$scalar[1] ? hexdec($scalar) : floatval($scalar);
494
case '.inf' === $scalarLower:
495
case '.nan' === $scalarLower:
497
case '-.inf' === $scalarLower:
499
case preg_match('/^(-|\+)?[0-9,]+(\.[0-9]+)?$/', $scalar):
500
return floatval(str_replace(',', '', $scalar));
501
case preg_match(self::getTimestampRegex(), $scalar):
502
return strtotime($scalar);
505
return (string) $scalar;
510
* Gets a regex that matches a YAML date.
512
* @return string The regular expression
514
* @see http://www.yaml.org/spec/1.2/spec.html#id2761573
516
private static function getTimestampRegex()
520
(?P<year>[0-9][0-9][0-9][0-9])
521
-(?P<month>[0-9][0-9]?)
522
-(?P<day>[0-9][0-9]?)
524
(?P<hour>[0-9][0-9]?)
525
:(?P<minute>[0-9][0-9])
526
:(?P<second>[0-9][0-9])
527
(?:\.(?P<fraction>[0-9]*))?
528
(?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
529
(?::(?P<tz_minute>[0-9][0-9]))?))?)?