annotate vendor/symfony/yaml/Inline.php @ 19:fa3358dc1485 tip

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