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 value.
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 mixed A PHP value
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);
55 if (2 /* MB_OVERLOAD_STRING */ & (int) ini_get('mbstring.func_overload')) {
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 value
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 = (string) $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'" : (string) $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 Parser
::preg_match(self
::getHexRegex(), $value):
153 case Parser
::preg_match(self
::getTimestampRegex(), $value):
154 return Escaper
::escapeWithSingleQuotes($value);
161 * Check if given array is hash or just normal indexed array.
165 * @param array $value The PHP array to check
167 * @return bool true if value is hash array, false otherwise
169 public static function isHash(array $value)
173 foreach ($value as $key => $val) {
174 if ($key !== $expectedKey++
) {
183 * Dumps a PHP array to a YAML string.
185 * @param array $value The PHP array to dump
186 * @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
187 * @param bool $objectSupport True if object support is enabled, false otherwise
189 * @return string The YAML string representing the PHP array
191 private static function dumpArray($value, $exceptionOnInvalidType, $objectSupport)
194 if ($value && !self
::isHash($value)) {
196 foreach ($value as $val) {
197 $output[] = self
::dump($val, $exceptionOnInvalidType, $objectSupport);
200 return sprintf('[%s]', implode(', ', $output));
205 foreach ($value as $key => $val) {
206 $output[] = sprintf('%s: %s', self
::dump($key, $exceptionOnInvalidType, $objectSupport), self
::dump($val, $exceptionOnInvalidType, $objectSupport));
209 return sprintf('{ %s }', implode(', ', $output));
213 * Parses a YAML scalar.
215 * @param string $scalar
216 * @param string[] $delimiters
217 * @param string[] $stringDelimiters
219 * @param bool $evaluate
220 * @param array $references
224 * @throws ParseException When malformed inline YAML string is parsed
228 public static function parseScalar($scalar, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true, $references = array())
230 if (in_array($scalar[$i], $stringDelimiters)) {
232 $output = self
::parseQuotedScalar($scalar, $i);
234 if (null !== $delimiters) {
235 $tmp = ltrim(substr($scalar, $i), ' ');
237 throw new ParseException(sprintf('Unexpected end of line, expected one of "%s".', implode($delimiters)));
239 if (!in_array($tmp[0], $delimiters)) {
240 throw new ParseException(sprintf('Unexpected characters (%s).', substr($scalar, $i)));
246 $output = substr($scalar, $i);
247 $i +
= strlen($output);
250 if (Parser
::preg_match('/[ \t]+#/', $output, $match, PREG_OFFSET_CAPTURE
)) {
251 $output = substr($output, 0, $match[0][1]);
253 } elseif (Parser
::preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) {
255 $i +
= strlen($output);
257 throw new ParseException(sprintf('Malformed inline YAML string: %s.', $scalar));
260 // a non-quoted string cannot start with @ or ` (reserved) nor with a scalar indicator (| or >)
261 if ($output && ('@' === $output[0] ||
'`' === $output[0] ||
'|' === $output[0] ||
'>' === $output[0])) {
262 @trigger_error
(sprintf('Not quoting the scalar "%s" starting with "%s" is deprecated since Symfony 2.8 and will throw a ParseException in 3.0.', $output, $output[0]), E_USER_DEPRECATED
);
264 // to be thrown in 3.0
265 // throw new ParseException(sprintf('The reserved indicator "%s" cannot start a plain scalar; you need to quote the scalar.', $output[0]));
269 $output = self
::evaluateScalar($output, $references);
277 * Parses a YAML quoted scalar.
279 * @param string $scalar
284 * @throws ParseException When malformed inline YAML string is parsed
286 private static function parseQuotedScalar($scalar, &$i)
288 if (!Parser
::preg_match('/'.self
::REGEX_QUOTED_STRING
.'/Au', substr($scalar, $i), $match)) {
289 throw new ParseException(sprintf('Malformed inline YAML string: %s.', substr($scalar, $i)));
292 $output = substr($match[0], 1, strlen($match[0]) - 2);
294 $unescaper = new Unescaper();
295 if ('"' == $scalar[$i]) {
296 $output = $unescaper->unescapeDoubleQuotedString($output);
298 $output = $unescaper->unescapeSingleQuotedString($output);
301 $i +
= strlen($match[0]);
307 * Parses a YAML sequence.
309 * @param string $sequence
311 * @param array $references
315 * @throws ParseException When malformed inline YAML string is parsed
317 private static function parseSequence($sequence, &$i = 0, $references = array())
320 $len = strlen($sequence);
325 switch ($sequence[$i]) {
328 $output[] = self
::parseSequence($sequence, $i, $references);
332 $output[] = self
::parseMapping($sequence, $i, $references);
340 $isQuoted = in_array($sequence[$i], array('"', "'"));
341 $value = self
::parseScalar($sequence, array(',', ']'), array('"', "'"), $i, true, $references);
343 // the value can be an array if a reference has been resolved to an array var
344 if (!is_array($value) && !$isQuoted && false !== strpos($value, ': ')) {
348 $value = self
::parseMapping('{'.$value.'}', $pos, $references);
349 } catch (\InvalidArgumentException
$e) {
362 throw new ParseException(sprintf('Malformed inline YAML string: %s.', $sequence));
366 * Parses a YAML mapping.
368 * @param string $mapping
370 * @param array $references
372 * @return array|\stdClass
374 * @throws ParseException When malformed inline YAML string is parsed
376 private static function parseMapping($mapping, &$i = 0, $references = array())
379 $len = strlen($mapping);
381 $allowOverwrite = false;
383 // {foo: bar, bar:foo, ...}
385 switch ($mapping[$i]) {
391 if (self
::$objectForMap) {
392 return (object) $output;
399 $key = self
::parseScalar($mapping, array(':', ' '), array('"', "'"), $i, false);
402 $allowOverwrite = true;
409 switch ($mapping[$i]) {
412 $value = self
::parseSequence($mapping, $i, $references);
413 // Spec: Keys MUST be unique; first one wins.
414 // Parser cannot abort this mapping earlier, since lines
415 // are processed sequentially.
416 // But overwriting is allowed when a merge node is used in current block.
418 foreach ($value as $parsedValue) {
419 $output +
= $parsedValue;
421 } elseif ($allowOverwrite ||
!isset($output[$key])) {
422 $output[$key] = $value;
428 $value = self
::parseMapping($mapping, $i, $references);
429 // Spec: Keys MUST be unique; first one wins.
430 // Parser cannot abort this mapping earlier, since lines
431 // are processed sequentially.
432 // But overwriting is allowed when a merge node is used in current block.
435 } elseif ($allowOverwrite ||
!isset($output[$key])) {
436 $output[$key] = $value;
444 $value = self
::parseScalar($mapping, array(',', '}'), array('"', "'"), $i, true, $references);
445 // Spec: Keys MUST be unique; first one wins.
446 // Parser cannot abort this mapping earlier, since lines
447 // are processed sequentially.
448 // But overwriting is allowed when a merge node is used in current block.
451 } elseif ($allowOverwrite ||
!isset($output[$key])) {
452 $output[$key] = $value;
466 throw new ParseException(sprintf('Malformed inline YAML string: %s.', $mapping));
470 * Evaluates scalars and replaces magic values.
472 * @param string $scalar
473 * @param array $references
475 * @return mixed The evaluated YAML string
477 * @throws ParseException when object parsing support was disabled and the parser detected a PHP object or when a reference could not be resolved
479 private static function evaluateScalar($scalar, $references = array())
481 $scalar = trim($scalar);
482 $scalarLower = strtolower($scalar);
484 if (0 === strpos($scalar, '*')) {
485 if (false !== $pos = strpos($scalar, '#')) {
486 $value = substr($scalar, 1, $pos - 2);
488 $value = substr($scalar, 1);
492 if (false === $value ||
'' === $value) {
493 throw new ParseException('A reference must contain at least one character.');
496 if (!array_key_exists($value, $references)) {
497 throw new ParseException(sprintf('Reference "%s" does not exist.', $value));
500 return $references[$value];
504 case 'null' === $scalarLower:
506 case '~' === $scalar:
508 case 'true' === $scalarLower:
510 case 'false' === $scalarLower:
512 // Optimise for returning strings.
513 case '+' === $scalar[0] ||
'-' === $scalar[0] ||
'.' === $scalar[0] ||
'!' === $scalar[0] ||
is_numeric($scalar[0]):
515 case 0 === strpos($scalar, '!str'):
516 return (string) substr($scalar, 5);
517 case 0 === strpos($scalar, '! '):
518 return (int) self
::parseScalar(substr($scalar, 2));
519 case 0 === strpos($scalar, '!php/object:'):
520 if (self
::$objectSupport) {
521 return unserialize(substr($scalar, 12));
524 if (self
::$exceptionOnInvalidType) {
525 throw new ParseException('Object support when parsing a YAML file has been disabled.');
529 case 0 === strpos($scalar, '!!php/object:'):
530 if (self
::$objectSupport) {
531 return unserialize(substr($scalar, 13));
534 if (self
::$exceptionOnInvalidType) {
535 throw new ParseException('Object support when parsing a YAML file has been disabled.');
539 case 0 === strpos($scalar, '!!float '):
540 return (float) substr($scalar, 8);
541 case ctype_digit($scalar):
543 $cast = (int) $scalar;
545 return '0' == $scalar[0] ?
octdec($scalar) : (((string) $raw == (string) $cast) ?
$cast : $raw);
546 case '-' === $scalar[0] && ctype_digit(substr($scalar, 1)):
548 $cast = (int) $scalar;
550 return '0' == $scalar[1] ?
octdec($scalar) : (((string) $raw === (string) $cast) ?
$cast : $raw);
551 case is_numeric($scalar):
552 case Parser
::preg_match(self
::getHexRegex(), $scalar):
553 return '0x' === $scalar[0].$scalar[1] ?
hexdec($scalar) : (float) $scalar;
554 case '.inf' === $scalarLower:
555 case '.nan' === $scalarLower:
557 case '-.inf' === $scalarLower:
559 case Parser
::preg_match('/^(-|\+)?[0-9,]+(\.[0-9]+)?$/', $scalar):
560 return (float) str_replace(',', '', $scalar);
561 case Parser
::preg_match(self
::getTimestampRegex(), $scalar):
562 $timeZone = date_default_timezone_get();
563 date_default_timezone_set('UTC');
564 $time = strtotime($scalar);
565 date_default_timezone_set($timeZone);
571 return (string) $scalar;
576 * Gets a regex that matches a YAML date.
578 * @return string The regular expression
580 * @see http://www.yaml.org/spec/1.2/spec.html#id2761573
582 private static function getTimestampRegex()
586 (?P<year>[0-9][0-9][0-9][0-9])
587 -(?P<month>[0-9][0-9]?)
588 -(?P<day>[0-9][0-9]?)
590 (?P<hour>[0-9][0-9]?)
591 :(?P<minute>[0-9][0-9])
592 :(?P<second>[0-9][0-9])
593 (?:\.(?P<fraction>[0-9]*))?
594 (?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
595 (?::(?P<tz_minute>[0-9][0-9]))?))?)?
601 * Gets a regex that matches a YAML number in hexadecimal notation.
605 private static function getHexRegex()
607 return '~^0x[0-9a-f]++$~i';