annotate vendor/symfony/yaml/Inline.php @ 0:c75dbcec494b

Initial commit from drush-created site
author Chris Cannam
date Thu, 05 Jul 2018 14:24:15 +0000
parents
children a9cd425dd02b
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 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@0 29 public static $parsedLineNumber = -1;
Chris@0 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@0 38 * @param int $flags
Chris@0 39 * @param int|null $parsedLineNumber
Chris@0 40 * @param string|null $parsedFilename
Chris@0 41 */
Chris@0 42 public static function initialize($flags, $parsedLineNumber = null, $parsedFilename = null)
Chris@0 43 {
Chris@0 44 self::$exceptionOnInvalidType = (bool) (Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE & $flags);
Chris@0 45 self::$objectSupport = (bool) (Yaml::PARSE_OBJECT & $flags);
Chris@0 46 self::$objectForMap = (bool) (Yaml::PARSE_OBJECT_FOR_MAP & $flags);
Chris@0 47 self::$constantSupport = (bool) (Yaml::PARSE_CONSTANT & $flags);
Chris@0 48 self::$parsedFilename = $parsedFilename;
Chris@0 49
Chris@0 50 if (null !== $parsedLineNumber) {
Chris@0 51 self::$parsedLineNumber = $parsedLineNumber;
Chris@0 52 }
Chris@0 53 }
Chris@0 54
Chris@0 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@0 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@0 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@0 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@0 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@0 114 $tag = self::parseTag($value, $i, $flags);
Chris@0 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@0 125 $result = self::parseScalar($value, $flags, null, $i, null === $tag, $references);
Chris@0 126 }
Chris@0 127
Chris@0 128 if (null !== $tag) {
Chris@0 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@0 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@0 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@0 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@0 184 if ($value instanceof TaggedValue) {
Chris@0 185 return '!'.$value->getTag().' '.self::dump($value->getValue(), $flags);
Chris@0 186 }
Chris@0 187
Chris@0 188 if (Yaml::DUMP_OBJECT & $flags) {
Chris@0 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@0 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@0 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@0 257 public static function isHash($value)
Chris@0 258 {
Chris@0 259 if ($value instanceof \stdClass || $value instanceof \ArrayObject) {
Chris@0 260 return true;
Chris@0 261 }
Chris@0 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@0 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@0 319 public static function parseScalar($scalar, $flags = 0, $delimiters = null, &$i = 0, $evaluate = true, $references = array(), $legacyOmittedKeySupport = false)
Chris@0 320 {
Chris@0 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 ('' === $tmp) {
Chris@0 328 throw new ParseException(sprintf('Unexpected end of line, expected one of "%s".', implode($delimiters)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
Chris@0 329 }
Chris@0 330 if (!in_array($tmp[0], $delimiters)) {
Chris@0 331 throw new ParseException(sprintf('Unexpected characters (%s).', substr($scalar, $i)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
Chris@0 332 }
Chris@0 333 }
Chris@0 334 } else {
Chris@0 335 // "normal" string
Chris@0 336 if (!$delimiters) {
Chris@0 337 $output = substr($scalar, $i);
Chris@0 338 $i += strlen($output);
Chris@0 339
Chris@0 340 // remove comments
Chris@0 341 if (Parser::preg_match('/[ \t]+#/', $output, $match, PREG_OFFSET_CAPTURE)) {
Chris@0 342 $output = substr($output, 0, $match[0][1]);
Chris@0 343 }
Chris@0 344 } elseif (Parser::preg_match('/^(.'.($legacyOmittedKeySupport ? '+' : '*').'?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) {
Chris@0 345 $output = $match[1];
Chris@0 346 $i += strlen($output);
Chris@0 347 } else {
Chris@0 348 throw new ParseException(sprintf('Malformed inline YAML string: %s.', $scalar), self::$parsedLineNumber + 1, null, self::$parsedFilename);
Chris@0 349 }
Chris@0 350
Chris@0 351 // a non-quoted string cannot start with @ or ` (reserved) nor with a scalar indicator (| or >)
Chris@0 352 if ($output && ('@' === $output[0] || '`' === $output[0] || '|' === $output[0] || '>' === $output[0])) {
Chris@0 353 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 354 }
Chris@0 355
Chris@0 356 if ($output && '%' === $output[0]) {
Chris@0 357 @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 358 }
Chris@0 359
Chris@0 360 if ($evaluate) {
Chris@0 361 $output = self::evaluateScalar($output, $flags, $references);
Chris@0 362 }
Chris@0 363 }
Chris@0 364
Chris@0 365 return $output;
Chris@0 366 }
Chris@0 367
Chris@0 368 /**
Chris@0 369 * Parses a YAML quoted scalar.
Chris@0 370 *
Chris@0 371 * @param string $scalar
Chris@0 372 * @param int &$i
Chris@0 373 *
Chris@0 374 * @return string
Chris@0 375 *
Chris@0 376 * @throws ParseException When malformed inline YAML string is parsed
Chris@0 377 */
Chris@0 378 private static function parseQuotedScalar($scalar, &$i)
Chris@0 379 {
Chris@0 380 if (!Parser::preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) {
Chris@0 381 throw new ParseException(sprintf('Malformed inline YAML string: %s.', substr($scalar, $i)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
Chris@0 382 }
Chris@0 383
Chris@0 384 $output = substr($match[0], 1, strlen($match[0]) - 2);
Chris@0 385
Chris@0 386 $unescaper = new Unescaper();
Chris@0 387 if ('"' == $scalar[$i]) {
Chris@0 388 $output = $unescaper->unescapeDoubleQuotedString($output);
Chris@0 389 } else {
Chris@0 390 $output = $unescaper->unescapeSingleQuotedString($output);
Chris@0 391 }
Chris@0 392
Chris@0 393 $i += strlen($match[0]);
Chris@0 394
Chris@0 395 return $output;
Chris@0 396 }
Chris@0 397
Chris@0 398 /**
Chris@0 399 * Parses a YAML sequence.
Chris@0 400 *
Chris@0 401 * @param string $sequence
Chris@0 402 * @param int $flags
Chris@0 403 * @param int &$i
Chris@0 404 * @param array $references
Chris@0 405 *
Chris@0 406 * @return array
Chris@0 407 *
Chris@0 408 * @throws ParseException When malformed inline YAML string is parsed
Chris@0 409 */
Chris@0 410 private static function parseSequence($sequence, $flags, &$i = 0, $references = array())
Chris@0 411 {
Chris@0 412 $output = array();
Chris@0 413 $len = strlen($sequence);
Chris@0 414 ++$i;
Chris@0 415
Chris@0 416 // [foo, bar, ...]
Chris@0 417 while ($i < $len) {
Chris@0 418 if (']' === $sequence[$i]) {
Chris@0 419 return $output;
Chris@0 420 }
Chris@0 421 if (',' === $sequence[$i] || ' ' === $sequence[$i]) {
Chris@0 422 ++$i;
Chris@0 423
Chris@0 424 continue;
Chris@0 425 }
Chris@0 426
Chris@0 427 $tag = self::parseTag($sequence, $i, $flags);
Chris@0 428 switch ($sequence[$i]) {
Chris@0 429 case '[':
Chris@0 430 // nested sequence
Chris@0 431 $value = self::parseSequence($sequence, $flags, $i, $references);
Chris@0 432 break;
Chris@0 433 case '{':
Chris@0 434 // nested mapping
Chris@0 435 $value = self::parseMapping($sequence, $flags, $i, $references);
Chris@0 436 break;
Chris@0 437 default:
Chris@0 438 $isQuoted = in_array($sequence[$i], array('"', "'"));
Chris@0 439 $value = self::parseScalar($sequence, $flags, array(',', ']'), $i, null === $tag, $references);
Chris@0 440
Chris@0 441 // the value can be an array if a reference has been resolved to an array var
Chris@0 442 if (is_string($value) && !$isQuoted && false !== strpos($value, ': ')) {
Chris@0 443 // embedded mapping?
Chris@0 444 try {
Chris@0 445 $pos = 0;
Chris@0 446 $value = self::parseMapping('{'.$value.'}', $flags, $pos, $references);
Chris@0 447 } catch (\InvalidArgumentException $e) {
Chris@0 448 // no, it's not
Chris@0 449 }
Chris@0 450 }
Chris@0 451
Chris@0 452 --$i;
Chris@0 453 }
Chris@0 454
Chris@0 455 if (null !== $tag) {
Chris@0 456 $value = new TaggedValue($tag, $value);
Chris@0 457 }
Chris@0 458
Chris@0 459 $output[] = $value;
Chris@0 460
Chris@0 461 ++$i;
Chris@0 462 }
Chris@0 463
Chris@0 464 throw new ParseException(sprintf('Malformed inline YAML string: %s.', $sequence), self::$parsedLineNumber + 1, null, self::$parsedFilename);
Chris@0 465 }
Chris@0 466
Chris@0 467 /**
Chris@0 468 * Parses a YAML mapping.
Chris@0 469 *
Chris@0 470 * @param string $mapping
Chris@0 471 * @param int $flags
Chris@0 472 * @param int &$i
Chris@0 473 * @param array $references
Chris@0 474 *
Chris@0 475 * @return array|\stdClass
Chris@0 476 *
Chris@0 477 * @throws ParseException When malformed inline YAML string is parsed
Chris@0 478 */
Chris@0 479 private static function parseMapping($mapping, $flags, &$i = 0, $references = array())
Chris@0 480 {
Chris@0 481 $output = array();
Chris@0 482 $len = strlen($mapping);
Chris@0 483 ++$i;
Chris@0 484 $allowOverwrite = false;
Chris@0 485
Chris@0 486 // {foo: bar, bar:foo, ...}
Chris@0 487 while ($i < $len) {
Chris@0 488 switch ($mapping[$i]) {
Chris@0 489 case ' ':
Chris@0 490 case ',':
Chris@0 491 ++$i;
Chris@0 492 continue 2;
Chris@0 493 case '}':
Chris@0 494 if (self::$objectForMap) {
Chris@0 495 return (object) $output;
Chris@0 496 }
Chris@0 497
Chris@0 498 return $output;
Chris@0 499 }
Chris@0 500
Chris@0 501 // key
Chris@0 502 $isKeyQuoted = in_array($mapping[$i], array('"', "'"), true);
Chris@0 503 $key = self::parseScalar($mapping, $flags, array(':', ' '), $i, false, array(), true);
Chris@0 504
Chris@0 505 if (':' !== $key && false === $i = strpos($mapping, ':', $i)) {
Chris@0 506 break;
Chris@0 507 }
Chris@0 508
Chris@0 509 if (':' === $key) {
Chris@0 510 @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 511 }
Chris@0 512
Chris@0 513 if (!$isKeyQuoted) {
Chris@0 514 $evaluatedKey = self::evaluateScalar($key, $flags, $references);
Chris@0 515
Chris@0 516 if ('' !== $key && $evaluatedKey !== $key && !is_string($evaluatedKey) && !is_int($evaluatedKey)) {
Chris@0 517 @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@0 518 }
Chris@0 519 }
Chris@0 520
Chris@0 521 if (':' !== $key && !$isKeyQuoted && (!isset($mapping[$i + 1]) || !in_array($mapping[$i + 1], array(' ', ',', '[', ']', '{', '}'), true))) {
Chris@0 522 @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@0 523 }
Chris@0 524
Chris@0 525 if ('<<' === $key) {
Chris@0 526 $allowOverwrite = true;
Chris@0 527 }
Chris@0 528
Chris@0 529 while ($i < $len) {
Chris@0 530 if (':' === $mapping[$i] || ' ' === $mapping[$i]) {
Chris@0 531 ++$i;
Chris@0 532
Chris@0 533 continue;
Chris@0 534 }
Chris@0 535
Chris@0 536 $tag = self::parseTag($mapping, $i, $flags);
Chris@0 537 switch ($mapping[$i]) {
Chris@0 538 case '[':
Chris@0 539 // nested sequence
Chris@0 540 $value = self::parseSequence($mapping, $flags, $i, $references);
Chris@0 541 // Spec: Keys MUST be unique; first one wins.
Chris@0 542 // Parser cannot abort this mapping earlier, since lines
Chris@0 543 // are processed sequentially.
Chris@0 544 // But overwriting is allowed when a merge node is used in current block.
Chris@0 545 if ('<<' === $key) {
Chris@0 546 foreach ($value as $parsedValue) {
Chris@0 547 $output += $parsedValue;
Chris@0 548 }
Chris@0 549 } elseif ($allowOverwrite || !isset($output[$key])) {
Chris@0 550 if (null !== $tag) {
Chris@0 551 $output[$key] = new TaggedValue($tag, $value);
Chris@0 552 } else {
Chris@0 553 $output[$key] = $value;
Chris@0 554 }
Chris@0 555 } elseif (isset($output[$key])) {
Chris@0 556 @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 557 }
Chris@0 558 break;
Chris@0 559 case '{':
Chris@0 560 // nested mapping
Chris@0 561 $value = self::parseMapping($mapping, $flags, $i, $references);
Chris@0 562 // Spec: Keys MUST be unique; first one wins.
Chris@0 563 // Parser cannot abort this mapping earlier, since lines
Chris@0 564 // are processed sequentially.
Chris@0 565 // But overwriting is allowed when a merge node is used in current block.
Chris@0 566 if ('<<' === $key) {
Chris@0 567 $output += $value;
Chris@0 568 } elseif ($allowOverwrite || !isset($output[$key])) {
Chris@0 569 if (null !== $tag) {
Chris@0 570 $output[$key] = new TaggedValue($tag, $value);
Chris@0 571 } else {
Chris@0 572 $output[$key] = $value;
Chris@0 573 }
Chris@0 574 } elseif (isset($output[$key])) {
Chris@0 575 @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 576 }
Chris@0 577 break;
Chris@0 578 default:
Chris@0 579 $value = self::parseScalar($mapping, $flags, array(',', '}'), $i, null === $tag, $references);
Chris@0 580 // Spec: Keys MUST be unique; first one wins.
Chris@0 581 // Parser cannot abort this mapping earlier, since lines
Chris@0 582 // are processed sequentially.
Chris@0 583 // But overwriting is allowed when a merge node is used in current block.
Chris@0 584 if ('<<' === $key) {
Chris@0 585 $output += $value;
Chris@0 586 } elseif ($allowOverwrite || !isset($output[$key])) {
Chris@0 587 if (null !== $tag) {
Chris@0 588 $output[$key] = new TaggedValue($tag, $value);
Chris@0 589 } else {
Chris@0 590 $output[$key] = $value;
Chris@0 591 }
Chris@0 592 } elseif (isset($output[$key])) {
Chris@0 593 @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 594 }
Chris@0 595 --$i;
Chris@0 596 }
Chris@0 597 ++$i;
Chris@0 598
Chris@0 599 continue 2;
Chris@0 600 }
Chris@0 601 }
Chris@0 602
Chris@0 603 throw new ParseException(sprintf('Malformed inline YAML string: %s.', $mapping), self::$parsedLineNumber + 1, null, self::$parsedFilename);
Chris@0 604 }
Chris@0 605
Chris@0 606 /**
Chris@0 607 * Evaluates scalars and replaces magic values.
Chris@0 608 *
Chris@0 609 * @param string $scalar
Chris@0 610 * @param int $flags
Chris@0 611 * @param array $references
Chris@0 612 *
Chris@0 613 * @return mixed The evaluated YAML string
Chris@0 614 *
Chris@0 615 * @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 616 */
Chris@0 617 private static function evaluateScalar($scalar, $flags, $references = array())
Chris@0 618 {
Chris@0 619 $scalar = trim($scalar);
Chris@0 620 $scalarLower = strtolower($scalar);
Chris@0 621
Chris@0 622 if (0 === strpos($scalar, '*')) {
Chris@0 623 if (false !== $pos = strpos($scalar, '#')) {
Chris@0 624 $value = substr($scalar, 1, $pos - 2);
Chris@0 625 } else {
Chris@0 626 $value = substr($scalar, 1);
Chris@0 627 }
Chris@0 628
Chris@0 629 // an unquoted *
Chris@0 630 if (false === $value || '' === $value) {
Chris@0 631 throw new ParseException('A reference must contain at least one character.', self::$parsedLineNumber + 1, $value, self::$parsedFilename);
Chris@0 632 }
Chris@0 633
Chris@0 634 if (!array_key_exists($value, $references)) {
Chris@0 635 throw new ParseException(sprintf('Reference "%s" does not exist.', $value), self::$parsedLineNumber + 1, $value, self::$parsedFilename);
Chris@0 636 }
Chris@0 637
Chris@0 638 return $references[$value];
Chris@0 639 }
Chris@0 640
Chris@0 641 switch (true) {
Chris@0 642 case 'null' === $scalarLower:
Chris@0 643 case '' === $scalar:
Chris@0 644 case '~' === $scalar:
Chris@0 645 return;
Chris@0 646 case 'true' === $scalarLower:
Chris@0 647 return true;
Chris@0 648 case 'false' === $scalarLower:
Chris@0 649 return false;
Chris@0 650 case '!' === $scalar[0]:
Chris@0 651 switch (true) {
Chris@0 652 case 0 === strpos($scalar, '!str'):
Chris@0 653 @trigger_error(self::getDeprecationMessage('Support for the !str tag is deprecated since Symfony 3.4. Use the !!str tag instead.'), E_USER_DEPRECATED);
Chris@0 654
Chris@0 655 return (string) substr($scalar, 5);
Chris@0 656 case 0 === strpos($scalar, '!!str '):
Chris@0 657 return (string) substr($scalar, 6);
Chris@0 658 case 0 === strpos($scalar, '! '):
Chris@0 659 @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@0 660
Chris@0 661 return (int) self::parseScalar(substr($scalar, 2), $flags);
Chris@0 662 case 0 === strpos($scalar, '!php/object:'):
Chris@0 663 if (self::$objectSupport) {
Chris@0 664 @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@0 665
Chris@0 666 return unserialize(substr($scalar, 12));
Chris@0 667 }
Chris@0 668
Chris@0 669 if (self::$exceptionOnInvalidType) {
Chris@0 670 throw new ParseException('Object support when parsing a YAML file has been disabled.', self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
Chris@0 671 }
Chris@0 672
Chris@0 673 return;
Chris@0 674 case 0 === strpos($scalar, '!!php/object:'):
Chris@0 675 if (self::$objectSupport) {
Chris@0 676 @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 677
Chris@0 678 return unserialize(substr($scalar, 13));
Chris@0 679 }
Chris@0 680
Chris@0 681 if (self::$exceptionOnInvalidType) {
Chris@0 682 throw new ParseException('Object support when parsing a YAML file has been disabled.', self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
Chris@0 683 }
Chris@0 684
Chris@0 685 return;
Chris@0 686 case 0 === strpos($scalar, '!php/object'):
Chris@0 687 if (self::$objectSupport) {
Chris@0 688 return unserialize(self::parseScalar(substr($scalar, 12)));
Chris@0 689 }
Chris@0 690
Chris@0 691 if (self::$exceptionOnInvalidType) {
Chris@0 692 throw new ParseException('Object support when parsing a YAML file has been disabled.', self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
Chris@0 693 }
Chris@0 694
Chris@0 695 return;
Chris@0 696 case 0 === strpos($scalar, '!php/const:'):
Chris@0 697 if (self::$constantSupport) {
Chris@0 698 @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@0 699
Chris@0 700 if (defined($const = substr($scalar, 11))) {
Chris@0 701 return constant($const);
Chris@0 702 }
Chris@0 703
Chris@0 704 throw new ParseException(sprintf('The constant "%s" is not defined.', $const), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
Chris@0 705 }
Chris@0 706 if (self::$exceptionOnInvalidType) {
Chris@0 707 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 708 }
Chris@0 709
Chris@0 710 return;
Chris@0 711 case 0 === strpos($scalar, '!php/const'):
Chris@0 712 if (self::$constantSupport) {
Chris@0 713 $i = 0;
Chris@0 714 if (defined($const = self::parseScalar(substr($scalar, 11), 0, null, $i, false))) {
Chris@0 715 return constant($const);
Chris@0 716 }
Chris@0 717
Chris@0 718 throw new ParseException(sprintf('The constant "%s" is not defined.', $const), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
Chris@0 719 }
Chris@0 720 if (self::$exceptionOnInvalidType) {
Chris@0 721 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 722 }
Chris@0 723
Chris@0 724 return;
Chris@0 725 case 0 === strpos($scalar, '!!float '):
Chris@0 726 return (float) substr($scalar, 8);
Chris@0 727 case 0 === strpos($scalar, '!!binary '):
Chris@0 728 return self::evaluateBinaryScalar(substr($scalar, 9));
Chris@0 729 default:
Chris@0 730 @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@0 731 }
Chris@0 732
Chris@0 733 // Optimize for returning strings.
Chris@0 734 // no break
Chris@0 735 case '+' === $scalar[0] || '-' === $scalar[0] || '.' === $scalar[0] || is_numeric($scalar[0]):
Chris@0 736 switch (true) {
Chris@0 737 case Parser::preg_match('{^[+-]?[0-9][0-9_]*$}', $scalar):
Chris@0 738 $scalar = str_replace('_', '', (string) $scalar);
Chris@0 739 // omitting the break / return as integers are handled in the next case
Chris@0 740 // no break
Chris@0 741 case ctype_digit($scalar):
Chris@0 742 $raw = $scalar;
Chris@0 743 $cast = (int) $scalar;
Chris@0 744
Chris@0 745 return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw);
Chris@0 746 case '-' === $scalar[0] && ctype_digit(substr($scalar, 1)):
Chris@0 747 $raw = $scalar;
Chris@0 748 $cast = (int) $scalar;
Chris@0 749
Chris@0 750 return '0' == $scalar[1] ? octdec($scalar) : (((string) $raw === (string) $cast) ? $cast : $raw);
Chris@0 751 case is_numeric($scalar):
Chris@0 752 case Parser::preg_match(self::getHexRegex(), $scalar):
Chris@0 753 $scalar = str_replace('_', '', $scalar);
Chris@0 754
Chris@0 755 return '0x' === $scalar[0].$scalar[1] ? hexdec($scalar) : (float) $scalar;
Chris@0 756 case '.inf' === $scalarLower:
Chris@0 757 case '.nan' === $scalarLower:
Chris@0 758 return -log(0);
Chris@0 759 case '-.inf' === $scalarLower:
Chris@0 760 return log(0);
Chris@0 761 case Parser::preg_match('/^(-|\+)?[0-9][0-9,]*(\.[0-9_]+)?$/', $scalar):
Chris@0 762 case Parser::preg_match('/^(-|\+)?[0-9][0-9_]*(\.[0-9_]+)?$/', $scalar):
Chris@0 763 if (false !== strpos($scalar, ',')) {
Chris@0 764 @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 765 }
Chris@0 766
Chris@0 767 return (float) str_replace(array(',', '_'), '', $scalar);
Chris@0 768 case Parser::preg_match(self::getTimestampRegex(), $scalar):
Chris@0 769 if (Yaml::PARSE_DATETIME & $flags) {
Chris@0 770 // When no timezone is provided in the parsed date, YAML spec says we must assume UTC.
Chris@0 771 return new \DateTime($scalar, new \DateTimeZone('UTC'));
Chris@0 772 }
Chris@0 773
Chris@0 774 $timeZone = date_default_timezone_get();
Chris@0 775 date_default_timezone_set('UTC');
Chris@0 776 $time = strtotime($scalar);
Chris@0 777 date_default_timezone_set($timeZone);
Chris@0 778
Chris@0 779 return $time;
Chris@0 780 }
Chris@0 781 }
Chris@0 782
Chris@0 783 return (string) $scalar;
Chris@0 784 }
Chris@0 785
Chris@0 786 /**
Chris@0 787 * @param string $value
Chris@0 788 * @param int &$i
Chris@0 789 * @param int $flags
Chris@0 790 *
Chris@0 791 * @return null|string
Chris@0 792 */
Chris@0 793 private static function parseTag($value, &$i, $flags)
Chris@0 794 {
Chris@0 795 if ('!' !== $value[$i]) {
Chris@0 796 return;
Chris@0 797 }
Chris@0 798
Chris@0 799 $tagLength = strcspn($value, " \t\n", $i + 1);
Chris@0 800 $tag = substr($value, $i + 1, $tagLength);
Chris@0 801
Chris@0 802 $nextOffset = $i + $tagLength + 1;
Chris@0 803 $nextOffset += strspn($value, ' ', $nextOffset);
Chris@0 804
Chris@0 805 // Is followed by a scalar
Chris@0 806 if ((!isset($value[$nextOffset]) || !in_array($value[$nextOffset], array('[', '{'), true)) && 'tagged' !== $tag) {
Chris@0 807 // Manage non-whitelisted scalars in {@link self::evaluateScalar()}
Chris@0 808 return;
Chris@0 809 }
Chris@0 810
Chris@0 811 // Built-in tags
Chris@0 812 if ($tag && '!' === $tag[0]) {
Chris@0 813 throw new ParseException(sprintf('The built-in tag "!%s" is not implemented.', $tag), self::$parsedLineNumber + 1, $value, self::$parsedFilename);
Chris@0 814 }
Chris@0 815
Chris@0 816 if (Yaml::PARSE_CUSTOM_TAGS & $flags) {
Chris@0 817 $i = $nextOffset;
Chris@0 818
Chris@0 819 return $tag;
Chris@0 820 }
Chris@0 821
Chris@0 822 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 823 }
Chris@0 824
Chris@0 825 /**
Chris@0 826 * @param string $scalar
Chris@0 827 *
Chris@0 828 * @return string
Chris@0 829 *
Chris@0 830 * @internal
Chris@0 831 */
Chris@0 832 public static function evaluateBinaryScalar($scalar)
Chris@0 833 {
Chris@0 834 $parsedBinaryData = self::parseScalar(preg_replace('/\s/', '', $scalar));
Chris@0 835
Chris@0 836 if (0 !== (strlen($parsedBinaryData) % 4)) {
Chris@0 837 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 838 }
Chris@0 839
Chris@0 840 if (!Parser::preg_match('#^[A-Z0-9+/]+={0,2}$#i', $parsedBinaryData)) {
Chris@0 841 throw new ParseException(sprintf('The base64 encoded data (%s) contains invalid characters.', $parsedBinaryData), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
Chris@0 842 }
Chris@0 843
Chris@0 844 return base64_decode($parsedBinaryData, true);
Chris@0 845 }
Chris@0 846
Chris@0 847 private static function isBinaryString($value)
Chris@0 848 {
Chris@0 849 return !preg_match('//u', $value) || preg_match('/[^\x00\x07-\x0d\x1B\x20-\xff]/', $value);
Chris@0 850 }
Chris@0 851
Chris@0 852 /**
Chris@0 853 * Gets a regex that matches a YAML date.
Chris@0 854 *
Chris@0 855 * @return string The regular expression
Chris@0 856 *
Chris@0 857 * @see http://www.yaml.org/spec/1.2/spec.html#id2761573
Chris@0 858 */
Chris@0 859 private static function getTimestampRegex()
Chris@0 860 {
Chris@0 861 return <<<EOF
Chris@0 862 ~^
Chris@0 863 (?P<year>[0-9][0-9][0-9][0-9])
Chris@0 864 -(?P<month>[0-9][0-9]?)
Chris@0 865 -(?P<day>[0-9][0-9]?)
Chris@0 866 (?:(?:[Tt]|[ \t]+)
Chris@0 867 (?P<hour>[0-9][0-9]?)
Chris@0 868 :(?P<minute>[0-9][0-9])
Chris@0 869 :(?P<second>[0-9][0-9])
Chris@0 870 (?:\.(?P<fraction>[0-9]*))?
Chris@0 871 (?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
Chris@0 872 (?::(?P<tz_minute>[0-9][0-9]))?))?)?
Chris@0 873 $~x
Chris@0 874 EOF;
Chris@0 875 }
Chris@0 876
Chris@0 877 /**
Chris@0 878 * Gets a regex that matches a YAML number in hexadecimal notation.
Chris@0 879 *
Chris@0 880 * @return string
Chris@0 881 */
Chris@0 882 private static function getHexRegex()
Chris@0 883 {
Chris@0 884 return '~^0x[0-9a-f_]++$~i';
Chris@0 885 }
Chris@0 886
Chris@0 887 private static function getDeprecationMessage($message)
Chris@0 888 {
Chris@0 889 $message = rtrim($message, '.');
Chris@0 890
Chris@0 891 if (null !== self::$parsedFilename) {
Chris@0 892 $message .= ' in '.self::$parsedFilename;
Chris@0 893 }
Chris@0 894
Chris@0 895 if (-1 !== self::$parsedLineNumber) {
Chris@0 896 $message .= ' on line '.(self::$parsedLineNumber + 1);
Chris@0 897 }
Chris@0 898
Chris@0 899 return $message.'.';
Chris@0 900 }
Chris@0 901 }