annotate vendor/symfony/yaml/Inline.php @ 12:7a779792577d

Update Drupal core to v8.4.5 (via Composer)
author Chris Cannam
date Fri, 23 Feb 2018 15:52:07 +0000
parents 4c8ae668cc8c
children 1fec387a4317
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 /*
Chris@0 4 * This file is part of the Symfony package.
Chris@0 5 *
Chris@0 6 * (c) Fabien Potencier <fabien@symfony.com>
Chris@0 7 *
Chris@0 8 * For the full copyright and license information, please view the LICENSE
Chris@0 9 * file that was distributed with this source code.
Chris@0 10 */
Chris@0 11
Chris@0 12 namespace Symfony\Component\Yaml;
Chris@0 13
Chris@0 14 use Symfony\Component\Yaml\Exception\ParseException;
Chris@0 15 use Symfony\Component\Yaml\Exception\DumpException;
Chris@0 16
Chris@0 17 /**
Chris@0 18 * Inline implements a YAML parser/dumper for the YAML inline syntax.
Chris@0 19 *
Chris@0 20 * @author Fabien Potencier <fabien@symfony.com>
Chris@0 21 *
Chris@0 22 * @internal
Chris@0 23 */
Chris@0 24 class Inline
Chris@0 25 {
Chris@0 26 const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*+(?:\\\\.[^"\\\\]*+)*+)"|\'([^\']*+(?:\'\'[^\']*+)*+)\')';
Chris@0 27
Chris@0 28 public static $parsedLineNumber;
Chris@0 29
Chris@0 30 private static $exceptionOnInvalidType = false;
Chris@0 31 private static $objectSupport = false;
Chris@0 32 private static $objectForMap = false;
Chris@0 33 private static $constantSupport = false;
Chris@0 34
Chris@0 35 /**
Chris@0 36 * Converts a YAML string to a PHP value.
Chris@0 37 *
Chris@0 38 * @param string $value A YAML string
Chris@0 39 * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior
Chris@0 40 * @param array $references Mapping of variable names to values
Chris@0 41 *
Chris@0 42 * @return mixed A PHP value
Chris@0 43 *
Chris@0 44 * @throws ParseException
Chris@0 45 */
Chris@0 46 public static function parse($value, $flags = 0, $references = array())
Chris@0 47 {
Chris@0 48 if (is_bool($flags)) {
Chris@0 49 @trigger_error('Passing a boolean flag to toggle exception handling is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED);
Chris@0 50
Chris@0 51 if ($flags) {
Chris@0 52 $flags = Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE;
Chris@0 53 } else {
Chris@0 54 $flags = 0;
Chris@0 55 }
Chris@0 56 }
Chris@0 57
Chris@0 58 if (func_num_args() >= 3 && !is_array($references)) {
Chris@0 59 @trigger_error('Passing a boolean flag to toggle object support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT flag instead.', E_USER_DEPRECATED);
Chris@0 60
Chris@0 61 if ($references) {
Chris@0 62 $flags |= Yaml::PARSE_OBJECT;
Chris@0 63 }
Chris@0 64
Chris@0 65 if (func_num_args() >= 4) {
Chris@0 66 @trigger_error('Passing a boolean flag to toggle object for map support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT_FOR_MAP flag instead.', E_USER_DEPRECATED);
Chris@0 67
Chris@0 68 if (func_get_arg(3)) {
Chris@0 69 $flags |= Yaml::PARSE_OBJECT_FOR_MAP;
Chris@0 70 }
Chris@0 71 }
Chris@0 72
Chris@0 73 if (func_num_args() >= 5) {
Chris@0 74 $references = func_get_arg(4);
Chris@0 75 } else {
Chris@0 76 $references = array();
Chris@0 77 }
Chris@0 78 }
Chris@0 79
Chris@0 80 self::$exceptionOnInvalidType = (bool) (Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE & $flags);
Chris@0 81 self::$objectSupport = (bool) (Yaml::PARSE_OBJECT & $flags);
Chris@0 82 self::$objectForMap = (bool) (Yaml::PARSE_OBJECT_FOR_MAP & $flags);
Chris@0 83 self::$constantSupport = (bool) (Yaml::PARSE_CONSTANT & $flags);
Chris@0 84
Chris@0 85 $value = trim($value);
Chris@0 86
Chris@0 87 if ('' === $value) {
Chris@0 88 return '';
Chris@0 89 }
Chris@0 90
Chris@0 91 if (2 /* MB_OVERLOAD_STRING */ & (int) ini_get('mbstring.func_overload')) {
Chris@0 92 $mbEncoding = mb_internal_encoding();
Chris@0 93 mb_internal_encoding('ASCII');
Chris@0 94 }
Chris@0 95
Chris@0 96 $i = 0;
Chris@0 97 switch ($value[0]) {
Chris@0 98 case '[':
Chris@0 99 $result = self::parseSequence($value, $flags, $i, $references);
Chris@0 100 ++$i;
Chris@0 101 break;
Chris@0 102 case '{':
Chris@0 103 $result = self::parseMapping($value, $flags, $i, $references);
Chris@0 104 ++$i;
Chris@0 105 break;
Chris@0 106 default:
Chris@0 107 $result = self::parseScalar($value, $flags, null, array('"', "'"), $i, true, $references);
Chris@0 108 }
Chris@0 109
Chris@0 110 // some comments are allowed at the end
Chris@0 111 if (preg_replace('/\s+#.*$/A', '', substr($value, $i))) {
Chris@0 112 throw new ParseException(sprintf('Unexpected characters near "%s".', substr($value, $i)));
Chris@0 113 }
Chris@0 114
Chris@0 115 if (isset($mbEncoding)) {
Chris@0 116 mb_internal_encoding($mbEncoding);
Chris@0 117 }
Chris@0 118
Chris@0 119 return $result;
Chris@0 120 }
Chris@0 121
Chris@0 122 /**
Chris@0 123 * Dumps a given PHP variable to a YAML string.
Chris@0 124 *
Chris@0 125 * @param mixed $value The PHP variable to convert
Chris@0 126 * @param int $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string
Chris@0 127 *
Chris@0 128 * @return string The YAML string representing the PHP value
Chris@0 129 *
Chris@0 130 * @throws DumpException When trying to dump PHP resource
Chris@0 131 */
Chris@0 132 public static function dump($value, $flags = 0)
Chris@0 133 {
Chris@0 134 if (is_bool($flags)) {
Chris@0 135 @trigger_error('Passing a boolean flag to toggle exception handling is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED);
Chris@0 136
Chris@0 137 if ($flags) {
Chris@0 138 $flags = Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE;
Chris@0 139 } else {
Chris@0 140 $flags = 0;
Chris@0 141 }
Chris@0 142 }
Chris@0 143
Chris@0 144 if (func_num_args() >= 3) {
Chris@0 145 @trigger_error('Passing a boolean flag to toggle object support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::DUMP_OBJECT flag instead.', E_USER_DEPRECATED);
Chris@0 146
Chris@0 147 if (func_get_arg(2)) {
Chris@0 148 $flags |= Yaml::DUMP_OBJECT;
Chris@0 149 }
Chris@0 150 }
Chris@0 151
Chris@0 152 switch (true) {
Chris@0 153 case is_resource($value):
Chris@0 154 if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) {
Chris@0 155 throw new DumpException(sprintf('Unable to dump PHP resources in a YAML file ("%s").', get_resource_type($value)));
Chris@0 156 }
Chris@0 157
Chris@0 158 return 'null';
Chris@0 159 case $value instanceof \DateTimeInterface:
Chris@0 160 return $value->format('c');
Chris@0 161 case is_object($value):
Chris@0 162 if (Yaml::DUMP_OBJECT & $flags) {
Chris@0 163 return '!php/object:'.serialize($value);
Chris@0 164 }
Chris@0 165
Chris@0 166 if (Yaml::DUMP_OBJECT_AS_MAP & $flags && ($value instanceof \stdClass || $value instanceof \ArrayObject)) {
Chris@12 167 return self::dumpArray($value, $flags);
Chris@0 168 }
Chris@0 169
Chris@0 170 if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) {
Chris@0 171 throw new DumpException('Object support when dumping a YAML file has been disabled.');
Chris@0 172 }
Chris@0 173
Chris@0 174 return 'null';
Chris@0 175 case is_array($value):
Chris@0 176 return self::dumpArray($value, $flags);
Chris@0 177 case null === $value:
Chris@0 178 return 'null';
Chris@0 179 case true === $value:
Chris@0 180 return 'true';
Chris@0 181 case false === $value:
Chris@0 182 return 'false';
Chris@0 183 case ctype_digit($value):
Chris@0 184 return is_string($value) ? "'$value'" : (int) $value;
Chris@0 185 case is_numeric($value):
Chris@0 186 $locale = setlocale(LC_NUMERIC, 0);
Chris@0 187 if (false !== $locale) {
Chris@0 188 setlocale(LC_NUMERIC, 'C');
Chris@0 189 }
Chris@0 190 if (is_float($value)) {
Chris@0 191 $repr = (string) $value;
Chris@0 192 if (is_infinite($value)) {
Chris@0 193 $repr = str_ireplace('INF', '.Inf', $repr);
Chris@0 194 } elseif (floor($value) == $value && $repr == $value) {
Chris@0 195 // Preserve float data type since storing a whole number will result in integer value.
Chris@0 196 $repr = '!!float '.$repr;
Chris@0 197 }
Chris@0 198 } else {
Chris@0 199 $repr = is_string($value) ? "'$value'" : (string) $value;
Chris@0 200 }
Chris@0 201 if (false !== $locale) {
Chris@0 202 setlocale(LC_NUMERIC, $locale);
Chris@0 203 }
Chris@0 204
Chris@0 205 return $repr;
Chris@0 206 case '' == $value:
Chris@0 207 return "''";
Chris@0 208 case self::isBinaryString($value):
Chris@0 209 return '!!binary '.base64_encode($value);
Chris@0 210 case Escaper::requiresDoubleQuoting($value):
Chris@0 211 return Escaper::escapeWithDoubleQuotes($value);
Chris@0 212 case Escaper::requiresSingleQuoting($value):
Chris@0 213 case Parser::preg_match('{^[0-9]+[_0-9]*$}', $value):
Chris@0 214 case Parser::preg_match(self::getHexRegex(), $value):
Chris@0 215 case Parser::preg_match(self::getTimestampRegex(), $value):
Chris@0 216 return Escaper::escapeWithSingleQuotes($value);
Chris@0 217 default:
Chris@0 218 return $value;
Chris@0 219 }
Chris@0 220 }
Chris@0 221
Chris@0 222 /**
Chris@0 223 * Check if given array is hash or just normal indexed array.
Chris@0 224 *
Chris@0 225 * @internal
Chris@0 226 *
Chris@12 227 * @param array|\ArrayObject|\stdClass $value The PHP array or array-like object to check
Chris@0 228 *
Chris@0 229 * @return bool true if value is hash array, false otherwise
Chris@0 230 */
Chris@12 231 public static function isHash($value)
Chris@0 232 {
Chris@12 233 if ($value instanceof \stdClass || $value instanceof \ArrayObject) {
Chris@12 234 return true;
Chris@12 235 }
Chris@12 236
Chris@0 237 $expectedKey = 0;
Chris@0 238
Chris@0 239 foreach ($value as $key => $val) {
Chris@0 240 if ($key !== $expectedKey++) {
Chris@0 241 return true;
Chris@0 242 }
Chris@0 243 }
Chris@0 244
Chris@0 245 return false;
Chris@0 246 }
Chris@0 247
Chris@0 248 /**
Chris@0 249 * Dumps a PHP array to a YAML string.
Chris@0 250 *
Chris@0 251 * @param array $value The PHP array to dump
Chris@0 252 * @param int $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string
Chris@0 253 *
Chris@0 254 * @return string The YAML string representing the PHP array
Chris@0 255 */
Chris@0 256 private static function dumpArray($value, $flags)
Chris@0 257 {
Chris@0 258 // array
Chris@0 259 if ($value && !self::isHash($value)) {
Chris@0 260 $output = array();
Chris@0 261 foreach ($value as $val) {
Chris@0 262 $output[] = self::dump($val, $flags);
Chris@0 263 }
Chris@0 264
Chris@0 265 return sprintf('[%s]', implode(', ', $output));
Chris@0 266 }
Chris@0 267
Chris@0 268 // hash
Chris@0 269 $output = array();
Chris@0 270 foreach ($value as $key => $val) {
Chris@0 271 $output[] = sprintf('%s: %s', self::dump($key, $flags), self::dump($val, $flags));
Chris@0 272 }
Chris@0 273
Chris@0 274 return sprintf('{ %s }', implode(', ', $output));
Chris@0 275 }
Chris@0 276
Chris@0 277 /**
Chris@0 278 * Parses a YAML scalar.
Chris@0 279 *
Chris@0 280 * @param string $scalar
Chris@0 281 * @param int $flags
Chris@0 282 * @param string[] $delimiters
Chris@0 283 * @param string[] $stringDelimiters
Chris@0 284 * @param int &$i
Chris@0 285 * @param bool $evaluate
Chris@0 286 * @param array $references
Chris@0 287 *
Chris@0 288 * @return string
Chris@0 289 *
Chris@0 290 * @throws ParseException When malformed inline YAML string is parsed
Chris@0 291 *
Chris@0 292 * @internal
Chris@0 293 */
Chris@0 294 public static function parseScalar($scalar, $flags = 0, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true, $references = array())
Chris@0 295 {
Chris@0 296 if (in_array($scalar[$i], $stringDelimiters)) {
Chris@0 297 // quoted scalar
Chris@0 298 $output = self::parseQuotedScalar($scalar, $i);
Chris@0 299
Chris@0 300 if (null !== $delimiters) {
Chris@0 301 $tmp = ltrim(substr($scalar, $i), ' ');
Chris@0 302 if (!in_array($tmp[0], $delimiters)) {
Chris@0 303 throw new ParseException(sprintf('Unexpected characters (%s).', substr($scalar, $i)));
Chris@0 304 }
Chris@0 305 }
Chris@0 306 } else {
Chris@0 307 // "normal" string
Chris@0 308 if (!$delimiters) {
Chris@0 309 $output = substr($scalar, $i);
Chris@0 310 $i += strlen($output);
Chris@0 311
Chris@0 312 // remove comments
Chris@0 313 if (Parser::preg_match('/[ \t]+#/', $output, $match, PREG_OFFSET_CAPTURE)) {
Chris@0 314 $output = substr($output, 0, $match[0][1]);
Chris@0 315 }
Chris@0 316 } elseif (Parser::preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) {
Chris@0 317 $output = $match[1];
Chris@0 318 $i += strlen($output);
Chris@0 319 } else {
Chris@0 320 throw new ParseException(sprintf('Malformed inline YAML string: %s.', $scalar));
Chris@0 321 }
Chris@0 322
Chris@0 323 // a non-quoted string cannot start with @ or ` (reserved) nor with a scalar indicator (| or >)
Chris@0 324 if ($output && ('@' === $output[0] || '`' === $output[0] || '|' === $output[0] || '>' === $output[0])) {
Chris@0 325 throw new ParseException(sprintf('The reserved indicator "%s" cannot start a plain scalar; you need to quote the scalar.', $output[0]));
Chris@0 326 }
Chris@0 327
Chris@0 328 if ($output && '%' === $output[0]) {
Chris@0 329 @trigger_error(sprintf('Not quoting the scalar "%s" starting with the "%%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0.', $output), E_USER_DEPRECATED);
Chris@0 330 }
Chris@0 331
Chris@0 332 if ($evaluate) {
Chris@0 333 $output = self::evaluateScalar($output, $flags, $references);
Chris@0 334 }
Chris@0 335 }
Chris@0 336
Chris@0 337 return $output;
Chris@0 338 }
Chris@0 339
Chris@0 340 /**
Chris@0 341 * Parses a YAML quoted scalar.
Chris@0 342 *
Chris@0 343 * @param string $scalar
Chris@0 344 * @param int &$i
Chris@0 345 *
Chris@0 346 * @return string
Chris@0 347 *
Chris@0 348 * @throws ParseException When malformed inline YAML string is parsed
Chris@0 349 */
Chris@0 350 private static function parseQuotedScalar($scalar, &$i)
Chris@0 351 {
Chris@0 352 if (!Parser::preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) {
Chris@0 353 throw new ParseException(sprintf('Malformed inline YAML string: %s.', substr($scalar, $i)));
Chris@0 354 }
Chris@0 355
Chris@0 356 $output = substr($match[0], 1, strlen($match[0]) - 2);
Chris@0 357
Chris@0 358 $unescaper = new Unescaper();
Chris@0 359 if ('"' == $scalar[$i]) {
Chris@0 360 $output = $unescaper->unescapeDoubleQuotedString($output);
Chris@0 361 } else {
Chris@0 362 $output = $unescaper->unescapeSingleQuotedString($output);
Chris@0 363 }
Chris@0 364
Chris@0 365 $i += strlen($match[0]);
Chris@0 366
Chris@0 367 return $output;
Chris@0 368 }
Chris@0 369
Chris@0 370 /**
Chris@0 371 * Parses a YAML sequence.
Chris@0 372 *
Chris@0 373 * @param string $sequence
Chris@0 374 * @param int $flags
Chris@0 375 * @param int &$i
Chris@0 376 * @param array $references
Chris@0 377 *
Chris@0 378 * @return array
Chris@0 379 *
Chris@0 380 * @throws ParseException When malformed inline YAML string is parsed
Chris@0 381 */
Chris@0 382 private static function parseSequence($sequence, $flags, &$i = 0, $references = array())
Chris@0 383 {
Chris@0 384 $output = array();
Chris@0 385 $len = strlen($sequence);
Chris@0 386 ++$i;
Chris@0 387
Chris@0 388 // [foo, bar, ...]
Chris@0 389 while ($i < $len) {
Chris@0 390 switch ($sequence[$i]) {
Chris@0 391 case '[':
Chris@0 392 // nested sequence
Chris@0 393 $output[] = self::parseSequence($sequence, $flags, $i, $references);
Chris@0 394 break;
Chris@0 395 case '{':
Chris@0 396 // nested mapping
Chris@0 397 $output[] = self::parseMapping($sequence, $flags, $i, $references);
Chris@0 398 break;
Chris@0 399 case ']':
Chris@0 400 return $output;
Chris@0 401 case ',':
Chris@0 402 case ' ':
Chris@0 403 break;
Chris@0 404 default:
Chris@0 405 $isQuoted = in_array($sequence[$i], array('"', "'"));
Chris@0 406 $value = self::parseScalar($sequence, $flags, array(',', ']'), array('"', "'"), $i, true, $references);
Chris@0 407
Chris@0 408 // the value can be an array if a reference has been resolved to an array var
Chris@0 409 if (is_string($value) && !$isQuoted && false !== strpos($value, ': ')) {
Chris@0 410 // embedded mapping?
Chris@0 411 try {
Chris@0 412 $pos = 0;
Chris@0 413 $value = self::parseMapping('{'.$value.'}', $flags, $pos, $references);
Chris@0 414 } catch (\InvalidArgumentException $e) {
Chris@0 415 // no, it's not
Chris@0 416 }
Chris@0 417 }
Chris@0 418
Chris@0 419 $output[] = $value;
Chris@0 420
Chris@0 421 --$i;
Chris@0 422 }
Chris@0 423
Chris@0 424 ++$i;
Chris@0 425 }
Chris@0 426
Chris@0 427 throw new ParseException(sprintf('Malformed inline YAML string: %s.', $sequence));
Chris@0 428 }
Chris@0 429
Chris@0 430 /**
Chris@0 431 * Parses a YAML mapping.
Chris@0 432 *
Chris@0 433 * @param string $mapping
Chris@0 434 * @param int $flags
Chris@0 435 * @param int &$i
Chris@0 436 * @param array $references
Chris@0 437 *
Chris@0 438 * @return array|\stdClass
Chris@0 439 *
Chris@0 440 * @throws ParseException When malformed inline YAML string is parsed
Chris@0 441 */
Chris@0 442 private static function parseMapping($mapping, $flags, &$i = 0, $references = array())
Chris@0 443 {
Chris@0 444 $output = array();
Chris@0 445 $len = strlen($mapping);
Chris@0 446 ++$i;
Chris@0 447
Chris@0 448 // {foo: bar, bar:foo, ...}
Chris@0 449 while ($i < $len) {
Chris@0 450 switch ($mapping[$i]) {
Chris@0 451 case ' ':
Chris@0 452 case ',':
Chris@0 453 ++$i;
Chris@0 454 continue 2;
Chris@0 455 case '}':
Chris@0 456 if (self::$objectForMap) {
Chris@0 457 return (object) $output;
Chris@0 458 }
Chris@0 459
Chris@0 460 return $output;
Chris@0 461 }
Chris@0 462
Chris@0 463 // key
Chris@12 464 $isKeyQuoted = in_array($mapping[$i], array('"', "'"), true);
Chris@0 465 $key = self::parseScalar($mapping, $flags, array(':', ' '), array('"', "'"), $i, false);
Chris@0 466
Chris@0 467 if (':' !== $key && false === $i = strpos($mapping, ':', $i)) {
Chris@0 468 break;
Chris@0 469 }
Chris@0 470
Chris@12 471 if (':' !== $key && !$isKeyQuoted && (!isset($mapping[$i + 1]) || !in_array($mapping[$i + 1], array(' ', ',', '[', ']', '{', '}'), true))) {
Chris@12 472 @trigger_error('Using a colon after an unquoted mapping key that is not followed by an indication character (i.e. " ", ",", "[", "]", "{", "}") is deprecated since version 3.2 and will throw a ParseException in 4.0.', E_USER_DEPRECATED);
Chris@0 473 }
Chris@0 474
Chris@0 475 // value
Chris@0 476 $done = false;
Chris@0 477
Chris@0 478 while ($i < $len) {
Chris@0 479 switch ($mapping[$i]) {
Chris@0 480 case '[':
Chris@0 481 // nested sequence
Chris@0 482 $value = self::parseSequence($mapping, $flags, $i, $references);
Chris@0 483 // Spec: Keys MUST be unique; first one wins.
Chris@0 484 // Parser cannot abort this mapping earlier, since lines
Chris@0 485 // are processed sequentially.
Chris@0 486 if (!isset($output[$key])) {
Chris@0 487 $output[$key] = $value;
Chris@0 488 } else {
Chris@0 489 @trigger_error(sprintf('Duplicate key "%s" detected on line %d whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated since version 3.2 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.', $key, self::$parsedLineNumber + 1), E_USER_DEPRECATED);
Chris@0 490 }
Chris@0 491 $done = true;
Chris@0 492 break;
Chris@0 493 case '{':
Chris@0 494 // nested mapping
Chris@0 495 $value = self::parseMapping($mapping, $flags, $i, $references);
Chris@0 496 // Spec: Keys MUST be unique; first one wins.
Chris@0 497 // Parser cannot abort this mapping earlier, since lines
Chris@0 498 // are processed sequentially.
Chris@0 499 if (!isset($output[$key])) {
Chris@0 500 $output[$key] = $value;
Chris@0 501 } else {
Chris@0 502 @trigger_error(sprintf('Duplicate key "%s" detected on line %d whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated since version 3.2 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.', $key, self::$parsedLineNumber + 1), E_USER_DEPRECATED);
Chris@0 503 }
Chris@0 504 $done = true;
Chris@0 505 break;
Chris@0 506 case ':':
Chris@0 507 case ' ':
Chris@0 508 break;
Chris@0 509 default:
Chris@0 510 $value = self::parseScalar($mapping, $flags, array(',', '}'), array('"', "'"), $i, true, $references);
Chris@0 511 // Spec: Keys MUST be unique; first one wins.
Chris@0 512 // Parser cannot abort this mapping earlier, since lines
Chris@0 513 // are processed sequentially.
Chris@0 514 if (!isset($output[$key])) {
Chris@0 515 $output[$key] = $value;
Chris@0 516 } else {
Chris@0 517 @trigger_error(sprintf('Duplicate key "%s" detected on line %d whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated since version 3.2 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.', $key, self::$parsedLineNumber + 1), E_USER_DEPRECATED);
Chris@0 518 }
Chris@0 519 $done = true;
Chris@0 520 --$i;
Chris@0 521 }
Chris@0 522
Chris@0 523 ++$i;
Chris@0 524
Chris@0 525 if ($done) {
Chris@0 526 continue 2;
Chris@0 527 }
Chris@0 528 }
Chris@0 529 }
Chris@0 530
Chris@0 531 throw new ParseException(sprintf('Malformed inline YAML string: %s.', $mapping));
Chris@0 532 }
Chris@0 533
Chris@0 534 /**
Chris@0 535 * Evaluates scalars and replaces magic values.
Chris@0 536 *
Chris@0 537 * @param string $scalar
Chris@0 538 * @param int $flags
Chris@0 539 * @param array $references
Chris@0 540 *
Chris@0 541 * @return mixed The evaluated YAML string
Chris@0 542 *
Chris@0 543 * @throws ParseException when object parsing support was disabled and the parser detected a PHP object or when a reference could not be resolved
Chris@0 544 */
Chris@0 545 private static function evaluateScalar($scalar, $flags, $references = array())
Chris@0 546 {
Chris@0 547 $scalar = trim($scalar);
Chris@0 548 $scalarLower = strtolower($scalar);
Chris@0 549
Chris@0 550 if (0 === strpos($scalar, '*')) {
Chris@0 551 if (false !== $pos = strpos($scalar, '#')) {
Chris@0 552 $value = substr($scalar, 1, $pos - 2);
Chris@0 553 } else {
Chris@0 554 $value = substr($scalar, 1);
Chris@0 555 }
Chris@0 556
Chris@0 557 // an unquoted *
Chris@0 558 if (false === $value || '' === $value) {
Chris@0 559 throw new ParseException('A reference must contain at least one character.');
Chris@0 560 }
Chris@0 561
Chris@0 562 if (!array_key_exists($value, $references)) {
Chris@0 563 throw new ParseException(sprintf('Reference "%s" does not exist.', $value));
Chris@0 564 }
Chris@0 565
Chris@0 566 return $references[$value];
Chris@0 567 }
Chris@0 568
Chris@0 569 switch (true) {
Chris@0 570 case 'null' === $scalarLower:
Chris@0 571 case '' === $scalar:
Chris@0 572 case '~' === $scalar:
Chris@0 573 return;
Chris@0 574 case 'true' === $scalarLower:
Chris@0 575 return true;
Chris@0 576 case 'false' === $scalarLower:
Chris@0 577 return false;
Chris@0 578 // Optimise for returning strings.
Chris@0 579 case $scalar[0] === '+' || $scalar[0] === '-' || $scalar[0] === '.' || $scalar[0] === '!' || is_numeric($scalar[0]):
Chris@0 580 switch (true) {
Chris@0 581 case 0 === strpos($scalar, '!str'):
Chris@0 582 return (string) substr($scalar, 5);
Chris@0 583 case 0 === strpos($scalar, '! '):
Chris@0 584 return (int) self::parseScalar(substr($scalar, 2), $flags);
Chris@0 585 case 0 === strpos($scalar, '!php/object:'):
Chris@0 586 if (self::$objectSupport) {
Chris@0 587 return unserialize(substr($scalar, 12));
Chris@0 588 }
Chris@0 589
Chris@0 590 if (self::$exceptionOnInvalidType) {
Chris@0 591 throw new ParseException('Object support when parsing a YAML file has been disabled.');
Chris@0 592 }
Chris@0 593
Chris@0 594 return;
Chris@0 595 case 0 === strpos($scalar, '!!php/object:'):
Chris@0 596 if (self::$objectSupport) {
Chris@0 597 @trigger_error('The !!php/object tag to indicate dumped PHP objects is deprecated since version 3.1 and will be removed in 4.0. Use the !php/object tag instead.', E_USER_DEPRECATED);
Chris@0 598
Chris@0 599 return unserialize(substr($scalar, 13));
Chris@0 600 }
Chris@0 601
Chris@0 602 if (self::$exceptionOnInvalidType) {
Chris@0 603 throw new ParseException('Object support when parsing a YAML file has been disabled.');
Chris@0 604 }
Chris@0 605
Chris@0 606 return;
Chris@0 607 case 0 === strpos($scalar, '!php/const:'):
Chris@0 608 if (self::$constantSupport) {
Chris@0 609 if (defined($const = substr($scalar, 11))) {
Chris@0 610 return constant($const);
Chris@0 611 }
Chris@0 612
Chris@0 613 throw new ParseException(sprintf('The constant "%s" is not defined.', $const));
Chris@0 614 }
Chris@0 615 if (self::$exceptionOnInvalidType) {
Chris@0 616 throw new ParseException(sprintf('The string "%s" could not be parsed as a constant. Have you forgotten to pass the "Yaml::PARSE_CONSTANT" flag to the parser?', $scalar));
Chris@0 617 }
Chris@0 618
Chris@0 619 return;
Chris@0 620 case 0 === strpos($scalar, '!!float '):
Chris@0 621 return (float) substr($scalar, 8);
Chris@0 622 case Parser::preg_match('{^[+-]?[0-9][0-9_]*$}', $scalar):
Chris@0 623 $scalar = str_replace('_', '', (string) $scalar);
Chris@0 624 // omitting the break / return as integers are handled in the next case
Chris@0 625 case ctype_digit($scalar):
Chris@0 626 $raw = $scalar;
Chris@0 627 $cast = (int) $scalar;
Chris@0 628
Chris@0 629 return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw);
Chris@0 630 case '-' === $scalar[0] && ctype_digit(substr($scalar, 1)):
Chris@0 631 $raw = $scalar;
Chris@0 632 $cast = (int) $scalar;
Chris@0 633
Chris@0 634 return '0' == $scalar[1] ? octdec($scalar) : (((string) $raw === (string) $cast) ? $cast : $raw);
Chris@0 635 case is_numeric($scalar):
Chris@0 636 case Parser::preg_match(self::getHexRegex(), $scalar):
Chris@0 637 $scalar = str_replace('_', '', $scalar);
Chris@0 638
Chris@0 639 return '0x' === $scalar[0].$scalar[1] ? hexdec($scalar) : (float) $scalar;
Chris@0 640 case '.inf' === $scalarLower:
Chris@0 641 case '.nan' === $scalarLower:
Chris@0 642 return -log(0);
Chris@0 643 case '-.inf' === $scalarLower:
Chris@0 644 return log(0);
Chris@0 645 case 0 === strpos($scalar, '!!binary '):
Chris@0 646 return self::evaluateBinaryScalar(substr($scalar, 9));
Chris@0 647 case Parser::preg_match('/^(-|\+)?[0-9][0-9,]*(\.[0-9_]+)?$/', $scalar):
Chris@0 648 case Parser::preg_match('/^(-|\+)?[0-9][0-9_]*(\.[0-9_]+)?$/', $scalar):
Chris@0 649 if (false !== strpos($scalar, ',')) {
Chris@0 650 @trigger_error('Using the comma as a group separator for floats is deprecated since version 3.2 and will be removed in 4.0.', E_USER_DEPRECATED);
Chris@0 651 }
Chris@0 652
Chris@0 653 return (float) str_replace(array(',', '_'), '', $scalar);
Chris@0 654 case Parser::preg_match(self::getTimestampRegex(), $scalar):
Chris@0 655 if (Yaml::PARSE_DATETIME & $flags) {
Chris@0 656 // When no timezone is provided in the parsed date, YAML spec says we must assume UTC.
Chris@0 657 return new \DateTime($scalar, new \DateTimeZone('UTC'));
Chris@0 658 }
Chris@0 659
Chris@0 660 $timeZone = date_default_timezone_get();
Chris@0 661 date_default_timezone_set('UTC');
Chris@0 662 $time = strtotime($scalar);
Chris@0 663 date_default_timezone_set($timeZone);
Chris@0 664
Chris@0 665 return $time;
Chris@0 666 }
Chris@0 667 default:
Chris@0 668 return (string) $scalar;
Chris@0 669 }
Chris@0 670 }
Chris@0 671
Chris@0 672 /**
Chris@0 673 * @param string $scalar
Chris@0 674 *
Chris@0 675 * @return string
Chris@0 676 *
Chris@0 677 * @internal
Chris@0 678 */
Chris@0 679 public static function evaluateBinaryScalar($scalar)
Chris@0 680 {
Chris@0 681 $parsedBinaryData = self::parseScalar(preg_replace('/\s/', '', $scalar));
Chris@0 682
Chris@0 683 if (0 !== (strlen($parsedBinaryData) % 4)) {
Chris@0 684 throw new ParseException(sprintf('The normalized base64 encoded data (data without whitespace characters) length must be a multiple of four (%d bytes given).', strlen($parsedBinaryData)));
Chris@0 685 }
Chris@0 686
Chris@0 687 if (!Parser::preg_match('#^[A-Z0-9+/]+={0,2}$#i', $parsedBinaryData)) {
Chris@0 688 throw new ParseException(sprintf('The base64 encoded data (%s) contains invalid characters.', $parsedBinaryData));
Chris@0 689 }
Chris@0 690
Chris@0 691 return base64_decode($parsedBinaryData, true);
Chris@0 692 }
Chris@0 693
Chris@0 694 private static function isBinaryString($value)
Chris@0 695 {
Chris@0 696 return !preg_match('//u', $value) || preg_match('/[^\x00\x07-\x0d\x1B\x20-\xff]/', $value);
Chris@0 697 }
Chris@0 698
Chris@0 699 /**
Chris@0 700 * Gets a regex that matches a YAML date.
Chris@0 701 *
Chris@0 702 * @return string The regular expression
Chris@0 703 *
Chris@0 704 * @see http://www.yaml.org/spec/1.2/spec.html#id2761573
Chris@0 705 */
Chris@0 706 private static function getTimestampRegex()
Chris@0 707 {
Chris@0 708 return <<<EOF
Chris@0 709 ~^
Chris@0 710 (?P<year>[0-9][0-9][0-9][0-9])
Chris@0 711 -(?P<month>[0-9][0-9]?)
Chris@0 712 -(?P<day>[0-9][0-9]?)
Chris@0 713 (?:(?:[Tt]|[ \t]+)
Chris@0 714 (?P<hour>[0-9][0-9]?)
Chris@0 715 :(?P<minute>[0-9][0-9])
Chris@0 716 :(?P<second>[0-9][0-9])
Chris@0 717 (?:\.(?P<fraction>[0-9]*))?
Chris@0 718 (?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
Chris@0 719 (?::(?P<tz_minute>[0-9][0-9]))?))?)?
Chris@0 720 $~x
Chris@0 721 EOF;
Chris@0 722 }
Chris@0 723
Chris@0 724 /**
Chris@0 725 * Gets a regex that matches a YAML number in hexadecimal notation.
Chris@0 726 *
Chris@0 727 * @return string
Chris@0 728 */
Chris@0 729 private static function getHexRegex()
Chris@0 730 {
Chris@0 731 return '~^0x[0-9a-f_]++$~i';
Chris@0 732 }
Chris@0 733 }