annotate vendor/symfony/yaml/Inline.php @ 14:1fec387a4317

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