annotate vendor/symfony/yaml/Parser.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@0 14 use Symfony\Component\Yaml\Exception\ParseException;
Chris@14 15 use Symfony\Component\Yaml\Tag\TaggedValue;
Chris@0 16
Chris@0 17 /**
Chris@0 18 * Parser parses YAML strings to convert them to PHP arrays.
Chris@0 19 *
Chris@0 20 * @author Fabien Potencier <fabien@symfony.com>
Chris@14 21 *
Chris@14 22 * @final since version 3.4
Chris@0 23 */
Chris@0 24 class Parser
Chris@0 25 {
Chris@14 26 const TAG_PATTERN = '(?P<tag>![\w!.\/:-]+)';
Chris@0 27 const BLOCK_SCALAR_HEADER_PATTERN = '(?P<separator>\||>)(?P<modifiers>\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P<comments> +#.*)?';
Chris@0 28
Chris@14 29 private $filename;
Chris@0 30 private $offset = 0;
Chris@0 31 private $totalNumberOfLines;
Chris@17 32 private $lines = [];
Chris@0 33 private $currentLineNb = -1;
Chris@0 34 private $currentLine = '';
Chris@17 35 private $refs = [];
Chris@17 36 private $skippedLineNumbers = [];
Chris@17 37 private $locallySkippedLineNumbers = [];
Chris@17 38 private $refsBeingParsed = [];
Chris@0 39
Chris@14 40 public function __construct()
Chris@14 41 {
Chris@17 42 if (\func_num_args() > 0) {
Chris@14 43 @trigger_error(sprintf('The constructor arguments $offset, $totalNumberOfLines, $skippedLineNumbers of %s are deprecated and will be removed in 4.0', self::class), E_USER_DEPRECATED);
Chris@14 44
Chris@14 45 $this->offset = func_get_arg(0);
Chris@17 46 if (\func_num_args() > 1) {
Chris@14 47 $this->totalNumberOfLines = func_get_arg(1);
Chris@14 48 }
Chris@17 49 if (\func_num_args() > 2) {
Chris@14 50 $this->skippedLineNumbers = func_get_arg(2);
Chris@14 51 }
Chris@14 52 }
Chris@14 53 }
Chris@14 54
Chris@0 55 /**
Chris@14 56 * Parses a YAML file into a PHP value.
Chris@0 57 *
Chris@14 58 * @param string $filename The path to the YAML file to be parsed
Chris@14 59 * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior
Chris@14 60 *
Chris@14 61 * @return mixed The YAML converted to a PHP value
Chris@14 62 *
Chris@14 63 * @throws ParseException If the file could not be read or the YAML is not valid
Chris@0 64 */
Chris@14 65 public function parseFile($filename, $flags = 0)
Chris@0 66 {
Chris@14 67 if (!is_file($filename)) {
Chris@14 68 throw new ParseException(sprintf('File "%s" does not exist.', $filename));
Chris@14 69 }
Chris@14 70
Chris@14 71 if (!is_readable($filename)) {
Chris@14 72 throw new ParseException(sprintf('File "%s" cannot be read.', $filename));
Chris@14 73 }
Chris@14 74
Chris@14 75 $this->filename = $filename;
Chris@14 76
Chris@14 77 try {
Chris@14 78 return $this->parse(file_get_contents($filename), $flags);
Chris@14 79 } finally {
Chris@14 80 $this->filename = null;
Chris@14 81 }
Chris@0 82 }
Chris@0 83
Chris@0 84 /**
Chris@0 85 * Parses a YAML string to a PHP value.
Chris@0 86 *
Chris@0 87 * @param string $value A YAML string
Chris@0 88 * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior
Chris@0 89 *
Chris@0 90 * @return mixed A PHP value
Chris@0 91 *
Chris@0 92 * @throws ParseException If the YAML is not valid
Chris@0 93 */
Chris@0 94 public function parse($value, $flags = 0)
Chris@0 95 {
Chris@17 96 if (\is_bool($flags)) {
Chris@14 97 @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 98
Chris@0 99 if ($flags) {
Chris@0 100 $flags = Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE;
Chris@0 101 } else {
Chris@0 102 $flags = 0;
Chris@0 103 }
Chris@0 104 }
Chris@0 105
Chris@17 106 if (\func_num_args() >= 3) {
Chris@14 107 @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 108
Chris@0 109 if (func_get_arg(2)) {
Chris@0 110 $flags |= Yaml::PARSE_OBJECT;
Chris@0 111 }
Chris@0 112 }
Chris@0 113
Chris@17 114 if (\func_num_args() >= 4) {
Chris@14 115 @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 116
Chris@0 117 if (func_get_arg(3)) {
Chris@0 118 $flags |= Yaml::PARSE_OBJECT_FOR_MAP;
Chris@0 119 }
Chris@0 120 }
Chris@0 121
Chris@14 122 if (Yaml::PARSE_KEYS_AS_STRINGS & $flags) {
Chris@14 123 @trigger_error('Using the Yaml::PARSE_KEYS_AS_STRINGS flag is deprecated since Symfony 3.4 as it will be removed in 4.0. Quote your keys when they are evaluable instead.', E_USER_DEPRECATED);
Chris@14 124 }
Chris@14 125
Chris@0 126 if (false === preg_match('//u', $value)) {
Chris@14 127 throw new ParseException('The YAML value does not appear to be valid UTF-8.', -1, null, $this->filename);
Chris@0 128 }
Chris@0 129
Chris@17 130 $this->refs = [];
Chris@0 131
Chris@0 132 $mbEncoding = null;
Chris@0 133 $e = null;
Chris@0 134 $data = null;
Chris@0 135
Chris@0 136 if (2 /* MB_OVERLOAD_STRING */ & (int) ini_get('mbstring.func_overload')) {
Chris@0 137 $mbEncoding = mb_internal_encoding();
Chris@0 138 mb_internal_encoding('UTF-8');
Chris@0 139 }
Chris@0 140
Chris@0 141 try {
Chris@0 142 $data = $this->doParse($value, $flags);
Chris@0 143 } catch (\Exception $e) {
Chris@0 144 } catch (\Throwable $e) {
Chris@0 145 }
Chris@0 146
Chris@0 147 if (null !== $mbEncoding) {
Chris@0 148 mb_internal_encoding($mbEncoding);
Chris@0 149 }
Chris@0 150
Chris@17 151 $this->lines = [];
Chris@0 152 $this->currentLine = '';
Chris@17 153 $this->refs = [];
Chris@17 154 $this->skippedLineNumbers = [];
Chris@17 155 $this->locallySkippedLineNumbers = [];
Chris@0 156
Chris@0 157 if (null !== $e) {
Chris@0 158 throw $e;
Chris@0 159 }
Chris@0 160
Chris@0 161 return $data;
Chris@0 162 }
Chris@0 163
Chris@0 164 private function doParse($value, $flags)
Chris@0 165 {
Chris@0 166 $this->currentLineNb = -1;
Chris@0 167 $this->currentLine = '';
Chris@0 168 $value = $this->cleanup($value);
Chris@0 169 $this->lines = explode("\n", $value);
Chris@17 170 $this->locallySkippedLineNumbers = [];
Chris@0 171
Chris@0 172 if (null === $this->totalNumberOfLines) {
Chris@17 173 $this->totalNumberOfLines = \count($this->lines);
Chris@0 174 }
Chris@0 175
Chris@14 176 if (!$this->moveToNextLine()) {
Chris@14 177 return null;
Chris@14 178 }
Chris@14 179
Chris@17 180 $data = [];
Chris@0 181 $context = null;
Chris@0 182 $allowOverwrite = false;
Chris@0 183
Chris@14 184 while ($this->isCurrentLineEmpty()) {
Chris@14 185 if (!$this->moveToNextLine()) {
Chris@14 186 return null;
Chris@14 187 }
Chris@14 188 }
Chris@14 189
Chris@14 190 // Resolves the tag and returns if end of the document
Chris@14 191 if (null !== ($tag = $this->getLineTag($this->currentLine, $flags, false)) && !$this->moveToNextLine()) {
Chris@14 192 return new TaggedValue($tag, '');
Chris@14 193 }
Chris@14 194
Chris@14 195 do {
Chris@0 196 if ($this->isCurrentLineEmpty()) {
Chris@0 197 continue;
Chris@0 198 }
Chris@0 199
Chris@0 200 // tab?
Chris@0 201 if ("\t" === $this->currentLine[0]) {
Chris@14 202 throw new ParseException('A YAML file cannot contain tabs as indentation.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
Chris@0 203 }
Chris@0 204
Chris@14 205 Inline::initialize($flags, $this->getRealCurrentLineNb(), $this->filename);
Chris@14 206
Chris@0 207 $isRef = $mergeNode = false;
Chris@0 208 if (self::preg_match('#^\-((?P<leadspaces>\s+)(?P<value>.+))?$#u', rtrim($this->currentLine), $values)) {
Chris@0 209 if ($context && 'mapping' == $context) {
Chris@14 210 throw new ParseException('You cannot define a sequence item when in a mapping', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
Chris@0 211 }
Chris@0 212 $context = 'sequence';
Chris@0 213
Chris@0 214 if (isset($values['value']) && self::preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#u', $values['value'], $matches)) {
Chris@0 215 $isRef = $matches['ref'];
Chris@17 216 $this->refsBeingParsed[] = $isRef;
Chris@0 217 $values['value'] = $matches['value'];
Chris@0 218 }
Chris@0 219
Chris@14 220 if (isset($values['value'][1]) && '?' === $values['value'][0] && ' ' === $values['value'][1]) {
Chris@14 221 @trigger_error($this->getDeprecationMessage('Starting an unquoted string with a question mark followed by a space is deprecated since Symfony 3.3 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.'), E_USER_DEPRECATED);
Chris@14 222 }
Chris@14 223
Chris@0 224 // array
Chris@0 225 if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) {
Chris@0 226 $data[] = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(null, true), $flags);
Chris@14 227 } elseif (null !== $subTag = $this->getLineTag(ltrim($values['value'], ' '), $flags)) {
Chris@14 228 $data[] = new TaggedValue(
Chris@14 229 $subTag,
Chris@14 230 $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(null, true), $flags)
Chris@14 231 );
Chris@0 232 } else {
Chris@0 233 if (isset($values['leadspaces'])
Chris@14 234 && self::preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{\[].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $this->trimTag($values['value']), $matches)
Chris@0 235 ) {
Chris@0 236 // this is a compact notation element, add to next block and parse
Chris@0 237 $block = $values['value'];
Chris@0 238 if ($this->isNextLineIndented()) {
Chris@17 239 $block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + \strlen($values['leadspaces']) + 1);
Chris@0 240 }
Chris@0 241
Chris@0 242 $data[] = $this->parseBlock($this->getRealCurrentLineNb(), $block, $flags);
Chris@0 243 } else {
Chris@0 244 $data[] = $this->parseValue($values['value'], $flags, $context);
Chris@0 245 }
Chris@0 246 }
Chris@0 247 if ($isRef) {
Chris@0 248 $this->refs[$isRef] = end($data);
Chris@17 249 array_pop($this->refsBeingParsed);
Chris@0 250 }
Chris@0 251 } elseif (
Chris@14 252 self::preg_match('#^(?P<key>(?:![^\s]++\s++)?(?:'.Inline::REGEX_QUOTED_STRING.'|(?:!?!php/const:)?[^ \'"\[\{!].*?)) *\:(\s++(?P<value>.+))?$#u', rtrim($this->currentLine), $values)
Chris@17 253 && (false === strpos($values['key'], ' #') || \in_array($values['key'][0], ['"', "'"]))
Chris@0 254 ) {
Chris@0 255 if ($context && 'sequence' == $context) {
Chris@14 256 throw new ParseException('You cannot define a mapping item when in a sequence', $this->currentLineNb + 1, $this->currentLine, $this->filename);
Chris@0 257 }
Chris@0 258 $context = 'mapping';
Chris@0 259
Chris@0 260 try {
Chris@14 261 $i = 0;
Chris@14 262 $evaluateKey = !(Yaml::PARSE_KEYS_AS_STRINGS & $flags);
Chris@14 263
Chris@14 264 // constants in key will be evaluated anyway
Chris@14 265 if (isset($values['key'][0]) && '!' === $values['key'][0] && Yaml::PARSE_CONSTANT & $flags) {
Chris@14 266 $evaluateKey = true;
Chris@14 267 }
Chris@14 268
Chris@14 269 $key = Inline::parseScalar($values['key'], 0, null, $i, $evaluateKey);
Chris@0 270 } catch (ParseException $e) {
Chris@0 271 $e->setParsedLine($this->getRealCurrentLineNb() + 1);
Chris@0 272 $e->setSnippet($this->currentLine);
Chris@0 273
Chris@0 274 throw $e;
Chris@0 275 }
Chris@0 276
Chris@17 277 if (!\is_string($key) && !\is_int($key)) {
Chris@14 278 $keyType = is_numeric($key) ? 'numeric key' : 'non-string key';
Chris@14 279 @trigger_error($this->getDeprecationMessage(sprintf('Implicit casting of %s to string is deprecated since Symfony 3.3 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0. Quote your evaluable mapping keys instead.', $keyType)), E_USER_DEPRECATED);
Chris@14 280 }
Chris@14 281
Chris@0 282 // Convert float keys to strings, to avoid being converted to integers by PHP
Chris@17 283 if (\is_float($key)) {
Chris@0 284 $key = (string) $key;
Chris@0 285 }
Chris@0 286
Chris@14 287 if ('<<' === $key && (!isset($values['value']) || !self::preg_match('#^&(?P<ref>[^ ]+)#u', $values['value'], $refMatches))) {
Chris@0 288 $mergeNode = true;
Chris@0 289 $allowOverwrite = true;
Chris@14 290 if (isset($values['value'][0]) && '*' === $values['value'][0]) {
Chris@14 291 $refName = substr(rtrim($values['value']), 1);
Chris@18 292 if (!\array_key_exists($refName, $this->refs)) {
Chris@17 293 if (false !== $pos = array_search($refName, $this->refsBeingParsed, true)) {
Chris@17 294 throw new ParseException(sprintf('Circular reference [%s, %s] detected for reference "%s".', implode(', ', \array_slice($this->refsBeingParsed, $pos)), $refName, $refName), $this->currentLineNb + 1, $this->currentLine, $this->filename);
Chris@17 295 }
Chris@17 296
Chris@14 297 throw new ParseException(sprintf('Reference "%s" does not exist.', $refName), $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
Chris@0 298 }
Chris@0 299
Chris@0 300 $refValue = $this->refs[$refName];
Chris@0 301
Chris@14 302 if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $refValue instanceof \stdClass) {
Chris@14 303 $refValue = (array) $refValue;
Chris@14 304 }
Chris@14 305
Chris@17 306 if (!\is_array($refValue)) {
Chris@14 307 throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
Chris@0 308 }
Chris@0 309
Chris@0 310 $data += $refValue; // array union
Chris@0 311 } else {
Chris@14 312 if (isset($values['value']) && '' !== $values['value']) {
Chris@0 313 $value = $values['value'];
Chris@0 314 } else {
Chris@0 315 $value = $this->getNextEmbedBlock();
Chris@0 316 }
Chris@0 317 $parsed = $this->parseBlock($this->getRealCurrentLineNb() + 1, $value, $flags);
Chris@0 318
Chris@14 319 if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $parsed instanceof \stdClass) {
Chris@14 320 $parsed = (array) $parsed;
Chris@14 321 }
Chris@14 322
Chris@17 323 if (!\is_array($parsed)) {
Chris@14 324 throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
Chris@0 325 }
Chris@0 326
Chris@0 327 if (isset($parsed[0])) {
Chris@0 328 // If the value associated with the merge key is a sequence, then this sequence is expected to contain mapping nodes
Chris@0 329 // and each of these nodes is merged in turn according to its order in the sequence. Keys in mapping nodes earlier
Chris@0 330 // in the sequence override keys specified in later mapping nodes.
Chris@0 331 foreach ($parsed as $parsedItem) {
Chris@14 332 if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $parsedItem instanceof \stdClass) {
Chris@14 333 $parsedItem = (array) $parsedItem;
Chris@14 334 }
Chris@14 335
Chris@17 336 if (!\is_array($parsedItem)) {
Chris@14 337 throw new ParseException('Merge items must be arrays.', $this->getRealCurrentLineNb() + 1, $parsedItem, $this->filename);
Chris@0 338 }
Chris@0 339
Chris@0 340 $data += $parsedItem; // array union
Chris@0 341 }
Chris@0 342 } else {
Chris@0 343 // If the value associated with the key is a single mapping node, each of its key/value pairs is inserted into the
Chris@0 344 // current mapping, unless the key already exists in it.
Chris@0 345 $data += $parsed; // array union
Chris@0 346 }
Chris@0 347 }
Chris@14 348 } elseif ('<<' !== $key && isset($values['value']) && self::preg_match('#^&(?P<ref>[^ ]++) *+(?P<value>.*)#u', $values['value'], $matches)) {
Chris@0 349 $isRef = $matches['ref'];
Chris@17 350 $this->refsBeingParsed[] = $isRef;
Chris@0 351 $values['value'] = $matches['value'];
Chris@0 352 }
Chris@0 353
Chris@14 354 $subTag = null;
Chris@0 355 if ($mergeNode) {
Chris@0 356 // Merge keys
Chris@14 357 } elseif (!isset($values['value']) || '' === $values['value'] || 0 === strpos($values['value'], '#') || (null !== $subTag = $this->getLineTag($values['value'], $flags)) || '<<' === $key) {
Chris@0 358 // hash
Chris@0 359 // if next line is less indented or equal, then it means that the current value is null
Chris@0 360 if (!$this->isNextLineIndented() && !$this->isNextLineUnIndentedCollection()) {
Chris@0 361 // Spec: Keys MUST be unique; first one wins.
Chris@0 362 // But overwriting is allowed when a merge node is used in current block.
Chris@0 363 if ($allowOverwrite || !isset($data[$key])) {
Chris@14 364 if (null !== $subTag) {
Chris@14 365 $data[$key] = new TaggedValue($subTag, '');
Chris@14 366 } else {
Chris@14 367 $data[$key] = null;
Chris@14 368 }
Chris@0 369 } else {
Chris@14 370 @trigger_error($this->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 371 }
Chris@0 372 } else {
Chris@0 373 $value = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(), $flags);
Chris@14 374 if ('<<' === $key) {
Chris@14 375 $this->refs[$refMatches['ref']] = $value;
Chris@14 376
Chris@14 377 if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $value instanceof \stdClass) {
Chris@14 378 $value = (array) $value;
Chris@14 379 }
Chris@14 380
Chris@14 381 $data += $value;
Chris@14 382 } elseif ($allowOverwrite || !isset($data[$key])) {
Chris@14 383 // Spec: Keys MUST be unique; first one wins.
Chris@14 384 // But overwriting is allowed when a merge node is used in current block.
Chris@14 385 if (null !== $subTag) {
Chris@14 386 $data[$key] = new TaggedValue($subTag, $value);
Chris@14 387 } else {
Chris@14 388 $data[$key] = $value;
Chris@14 389 }
Chris@0 390 } else {
Chris@14 391 @trigger_error($this->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 392 }
Chris@0 393 }
Chris@0 394 } else {
Chris@14 395 $value = $this->parseValue(rtrim($values['value']), $flags, $context);
Chris@0 396 // Spec: Keys MUST be unique; first one wins.
Chris@0 397 // But overwriting is allowed when a merge node is used in current block.
Chris@0 398 if ($allowOverwrite || !isset($data[$key])) {
Chris@0 399 $data[$key] = $value;
Chris@0 400 } else {
Chris@14 401 @trigger_error($this->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 402 }
Chris@0 403 }
Chris@0 404 if ($isRef) {
Chris@0 405 $this->refs[$isRef] = $data[$key];
Chris@17 406 array_pop($this->refsBeingParsed);
Chris@0 407 }
Chris@0 408 } else {
Chris@0 409 // multiple documents are not supported
Chris@0 410 if ('---' === $this->currentLine) {
Chris@14 411 throw new ParseException('Multiple documents are not supported.', $this->currentLineNb + 1, $this->currentLine, $this->filename);
Chris@14 412 }
Chris@14 413
Chris@14 414 if ($deprecatedUsage = (isset($this->currentLine[1]) && '?' === $this->currentLine[0] && ' ' === $this->currentLine[1])) {
Chris@14 415 @trigger_error($this->getDeprecationMessage('Starting an unquoted string with a question mark followed by a space is deprecated since Symfony 3.3 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.'), E_USER_DEPRECATED);
Chris@0 416 }
Chris@0 417
Chris@0 418 // 1-liner optionally followed by newline(s)
Chris@17 419 if (\is_string($value) && $this->lines[0] === trim($value)) {
Chris@0 420 try {
Chris@0 421 $value = Inline::parse($this->lines[0], $flags, $this->refs);
Chris@0 422 } catch (ParseException $e) {
Chris@0 423 $e->setParsedLine($this->getRealCurrentLineNb() + 1);
Chris@0 424 $e->setSnippet($this->currentLine);
Chris@0 425
Chris@0 426 throw $e;
Chris@0 427 }
Chris@0 428
Chris@0 429 return $value;
Chris@0 430 }
Chris@0 431
Chris@14 432 // try to parse the value as a multi-line string as a last resort
Chris@14 433 if (0 === $this->currentLineNb) {
Chris@14 434 $previousLineWasNewline = false;
Chris@14 435 $previousLineWasTerminatedWithBackslash = false;
Chris@14 436 $value = '';
Chris@14 437
Chris@14 438 foreach ($this->lines as $line) {
Chris@14 439 // If the indentation is not consistent at offset 0, it is to be considered as a ParseError
Chris@14 440 if (0 === $this->offset && !$deprecatedUsage && isset($line[0]) && ' ' === $line[0]) {
Chris@14 441 throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
Chris@14 442 }
Chris@14 443 if ('' === trim($line)) {
Chris@14 444 $value .= "\n";
Chris@14 445 } elseif (!$previousLineWasNewline && !$previousLineWasTerminatedWithBackslash) {
Chris@14 446 $value .= ' ';
Chris@14 447 }
Chris@14 448
Chris@14 449 if ('' !== trim($line) && '\\' === substr($line, -1)) {
Chris@14 450 $value .= ltrim(substr($line, 0, -1));
Chris@14 451 } elseif ('' !== trim($line)) {
Chris@14 452 $value .= trim($line);
Chris@14 453 }
Chris@14 454
Chris@14 455 if ('' === trim($line)) {
Chris@14 456 $previousLineWasNewline = true;
Chris@14 457 $previousLineWasTerminatedWithBackslash = false;
Chris@14 458 } elseif ('\\' === substr($line, -1)) {
Chris@14 459 $previousLineWasNewline = false;
Chris@14 460 $previousLineWasTerminatedWithBackslash = true;
Chris@14 461 } else {
Chris@14 462 $previousLineWasNewline = false;
Chris@14 463 $previousLineWasTerminatedWithBackslash = false;
Chris@14 464 }
Chris@14 465 }
Chris@14 466
Chris@14 467 try {
Chris@14 468 return Inline::parse(trim($value));
Chris@14 469 } catch (ParseException $e) {
Chris@14 470 // fall-through to the ParseException thrown below
Chris@14 471 }
Chris@14 472 }
Chris@14 473
Chris@14 474 throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
Chris@0 475 }
Chris@14 476 } while ($this->moveToNextLine());
Chris@14 477
Chris@14 478 if (null !== $tag) {
Chris@14 479 $data = new TaggedValue($tag, $data);
Chris@0 480 }
Chris@0 481
Chris@17 482 if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && !\is_object($data) && 'mapping' === $context) {
Chris@0 483 $object = new \stdClass();
Chris@0 484
Chris@0 485 foreach ($data as $key => $value) {
Chris@0 486 $object->$key = $value;
Chris@0 487 }
Chris@0 488
Chris@0 489 $data = $object;
Chris@0 490 }
Chris@0 491
Chris@0 492 return empty($data) ? null : $data;
Chris@0 493 }
Chris@0 494
Chris@0 495 private function parseBlock($offset, $yaml, $flags)
Chris@0 496 {
Chris@0 497 $skippedLineNumbers = $this->skippedLineNumbers;
Chris@0 498
Chris@0 499 foreach ($this->locallySkippedLineNumbers as $lineNumber) {
Chris@0 500 if ($lineNumber < $offset) {
Chris@0 501 continue;
Chris@0 502 }
Chris@0 503
Chris@0 504 $skippedLineNumbers[] = $lineNumber;
Chris@0 505 }
Chris@0 506
Chris@14 507 $parser = new self();
Chris@14 508 $parser->offset = $offset;
Chris@14 509 $parser->totalNumberOfLines = $this->totalNumberOfLines;
Chris@14 510 $parser->skippedLineNumbers = $skippedLineNumbers;
Chris@0 511 $parser->refs = &$this->refs;
Chris@17 512 $parser->refsBeingParsed = $this->refsBeingParsed;
Chris@0 513
Chris@0 514 return $parser->doParse($yaml, $flags);
Chris@0 515 }
Chris@0 516
Chris@0 517 /**
Chris@0 518 * Returns the current line number (takes the offset into account).
Chris@0 519 *
Chris@14 520 * @internal
Chris@14 521 *
Chris@0 522 * @return int The current line number
Chris@0 523 */
Chris@14 524 public function getRealCurrentLineNb()
Chris@0 525 {
Chris@0 526 $realCurrentLineNumber = $this->currentLineNb + $this->offset;
Chris@0 527
Chris@0 528 foreach ($this->skippedLineNumbers as $skippedLineNumber) {
Chris@0 529 if ($skippedLineNumber > $realCurrentLineNumber) {
Chris@0 530 break;
Chris@0 531 }
Chris@0 532
Chris@0 533 ++$realCurrentLineNumber;
Chris@0 534 }
Chris@0 535
Chris@0 536 return $realCurrentLineNumber;
Chris@0 537 }
Chris@0 538
Chris@0 539 /**
Chris@0 540 * Returns the current line indentation.
Chris@0 541 *
Chris@0 542 * @return int The current line indentation
Chris@0 543 */
Chris@0 544 private function getCurrentLineIndentation()
Chris@0 545 {
Chris@17 546 return \strlen($this->currentLine) - \strlen(ltrim($this->currentLine, ' '));
Chris@0 547 }
Chris@0 548
Chris@0 549 /**
Chris@0 550 * Returns the next embed block of YAML.
Chris@0 551 *
Chris@0 552 * @param int $indentation The indent level at which the block is to be read, or null for default
Chris@0 553 * @param bool $inSequence True if the enclosing data structure is a sequence
Chris@0 554 *
Chris@0 555 * @return string A YAML string
Chris@0 556 *
Chris@0 557 * @throws ParseException When indentation problem are detected
Chris@0 558 */
Chris@0 559 private function getNextEmbedBlock($indentation = null, $inSequence = false)
Chris@0 560 {
Chris@0 561 $oldLineIndentation = $this->getCurrentLineIndentation();
Chris@0 562
Chris@0 563 if (!$this->moveToNextLine()) {
Chris@0 564 return;
Chris@0 565 }
Chris@0 566
Chris@0 567 if (null === $indentation) {
Chris@14 568 $newIndent = null;
Chris@14 569 $movements = 0;
Chris@14 570
Chris@14 571 do {
Chris@14 572 $EOF = false;
Chris@14 573
Chris@14 574 // empty and comment-like lines do not influence the indentation depth
Chris@14 575 if ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()) {
Chris@14 576 $EOF = !$this->moveToNextLine();
Chris@14 577
Chris@14 578 if (!$EOF) {
Chris@14 579 ++$movements;
Chris@14 580 }
Chris@14 581 } else {
Chris@14 582 $newIndent = $this->getCurrentLineIndentation();
Chris@14 583 }
Chris@14 584 } while (!$EOF && null === $newIndent);
Chris@14 585
Chris@14 586 for ($i = 0; $i < $movements; ++$i) {
Chris@14 587 $this->moveToPreviousLine();
Chris@14 588 }
Chris@0 589
Chris@0 590 $unindentedEmbedBlock = $this->isStringUnIndentedCollectionItem();
Chris@0 591
Chris@0 592 if (!$this->isCurrentLineEmpty() && 0 === $newIndent && !$unindentedEmbedBlock) {
Chris@14 593 throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
Chris@0 594 }
Chris@0 595 } else {
Chris@0 596 $newIndent = $indentation;
Chris@0 597 }
Chris@0 598
Chris@17 599 $data = [];
Chris@0 600 if ($this->getCurrentLineIndentation() >= $newIndent) {
Chris@0 601 $data[] = substr($this->currentLine, $newIndent);
Chris@14 602 } elseif ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()) {
Chris@14 603 $data[] = $this->currentLine;
Chris@0 604 } else {
Chris@0 605 $this->moveToPreviousLine();
Chris@0 606
Chris@0 607 return;
Chris@0 608 }
Chris@0 609
Chris@0 610 if ($inSequence && $oldLineIndentation === $newIndent && isset($data[0][0]) && '-' === $data[0][0]) {
Chris@0 611 // the previous line contained a dash but no item content, this line is a sequence item with the same indentation
Chris@0 612 // and therefore no nested list or mapping
Chris@0 613 $this->moveToPreviousLine();
Chris@0 614
Chris@0 615 return;
Chris@0 616 }
Chris@0 617
Chris@0 618 $isItUnindentedCollection = $this->isStringUnIndentedCollectionItem();
Chris@0 619
Chris@0 620 while ($this->moveToNextLine()) {
Chris@0 621 $indent = $this->getCurrentLineIndentation();
Chris@0 622
Chris@0 623 if ($isItUnindentedCollection && !$this->isCurrentLineEmpty() && !$this->isStringUnIndentedCollectionItem() && $newIndent === $indent) {
Chris@0 624 $this->moveToPreviousLine();
Chris@0 625 break;
Chris@0 626 }
Chris@0 627
Chris@0 628 if ($this->isCurrentLineBlank()) {
Chris@0 629 $data[] = substr($this->currentLine, $newIndent);
Chris@0 630 continue;
Chris@0 631 }
Chris@0 632
Chris@0 633 if ($indent >= $newIndent) {
Chris@0 634 $data[] = substr($this->currentLine, $newIndent);
Chris@14 635 } elseif ($this->isCurrentLineComment()) {
Chris@14 636 $data[] = $this->currentLine;
Chris@0 637 } elseif (0 == $indent) {
Chris@0 638 $this->moveToPreviousLine();
Chris@0 639
Chris@0 640 break;
Chris@0 641 } else {
Chris@14 642 throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
Chris@0 643 }
Chris@0 644 }
Chris@0 645
Chris@0 646 return implode("\n", $data);
Chris@0 647 }
Chris@0 648
Chris@0 649 /**
Chris@0 650 * Moves the parser to the next line.
Chris@0 651 *
Chris@0 652 * @return bool
Chris@0 653 */
Chris@0 654 private function moveToNextLine()
Chris@0 655 {
Chris@17 656 if ($this->currentLineNb >= \count($this->lines) - 1) {
Chris@0 657 return false;
Chris@0 658 }
Chris@0 659
Chris@0 660 $this->currentLine = $this->lines[++$this->currentLineNb];
Chris@0 661
Chris@0 662 return true;
Chris@0 663 }
Chris@0 664
Chris@0 665 /**
Chris@0 666 * Moves the parser to the previous line.
Chris@0 667 *
Chris@0 668 * @return bool
Chris@0 669 */
Chris@0 670 private function moveToPreviousLine()
Chris@0 671 {
Chris@0 672 if ($this->currentLineNb < 1) {
Chris@0 673 return false;
Chris@0 674 }
Chris@0 675
Chris@0 676 $this->currentLine = $this->lines[--$this->currentLineNb];
Chris@0 677
Chris@0 678 return true;
Chris@0 679 }
Chris@0 680
Chris@0 681 /**
Chris@0 682 * Parses a YAML value.
Chris@0 683 *
Chris@0 684 * @param string $value A YAML value
Chris@0 685 * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior
Chris@0 686 * @param string $context The parser context (either sequence or mapping)
Chris@0 687 *
Chris@0 688 * @return mixed A PHP value
Chris@0 689 *
Chris@0 690 * @throws ParseException When reference does not exist
Chris@0 691 */
Chris@0 692 private function parseValue($value, $flags, $context)
Chris@0 693 {
Chris@0 694 if (0 === strpos($value, '*')) {
Chris@0 695 if (false !== $pos = strpos($value, '#')) {
Chris@0 696 $value = substr($value, 1, $pos - 2);
Chris@0 697 } else {
Chris@0 698 $value = substr($value, 1);
Chris@0 699 }
Chris@0 700
Chris@18 701 if (!\array_key_exists($value, $this->refs)) {
Chris@17 702 if (false !== $pos = array_search($value, $this->refsBeingParsed, true)) {
Chris@17 703 throw new ParseException(sprintf('Circular reference [%s, %s] detected for reference "%s".', implode(', ', \array_slice($this->refsBeingParsed, $pos)), $value, $value), $this->currentLineNb + 1, $this->currentLine, $this->filename);
Chris@17 704 }
Chris@17 705
Chris@14 706 throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLineNb + 1, $this->currentLine, $this->filename);
Chris@0 707 }
Chris@0 708
Chris@0 709 return $this->refs[$value];
Chris@0 710 }
Chris@0 711
Chris@14 712 if (self::preg_match('/^(?:'.self::TAG_PATTERN.' +)?'.self::BLOCK_SCALAR_HEADER_PATTERN.'$/', $value, $matches)) {
Chris@0 713 $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
Chris@0 714
Chris@0 715 $data = $this->parseBlockScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), (int) abs($modifiers));
Chris@0 716
Chris@14 717 if ('' !== $matches['tag']) {
Chris@14 718 if ('!!binary' === $matches['tag']) {
Chris@14 719 return Inline::evaluateBinaryScalar($data);
Chris@14 720 } elseif ('tagged' === $matches['tag']) {
Chris@14 721 return new TaggedValue(substr($matches['tag'], 1), $data);
Chris@14 722 } elseif ('!' !== $matches['tag']) {
Chris@14 723 @trigger_error($this->getDeprecationMessage(sprintf('Using the custom tag "%s" for the value "%s" is deprecated since Symfony 3.3. It will be replaced by an instance of %s in 4.0.', $matches['tag'], $data, TaggedValue::class)), E_USER_DEPRECATED);
Chris@14 724 }
Chris@0 725 }
Chris@0 726
Chris@0 727 return $data;
Chris@0 728 }
Chris@0 729
Chris@0 730 try {
Chris@0 731 $quotation = '' !== $value && ('"' === $value[0] || "'" === $value[0]) ? $value[0] : null;
Chris@0 732
Chris@0 733 // do not take following lines into account when the current line is a quoted single line value
Chris@14 734 if (null !== $quotation && self::preg_match('/^'.$quotation.'.*'.$quotation.'(\s*#.*)?$/', $value)) {
Chris@0 735 return Inline::parse($value, $flags, $this->refs);
Chris@0 736 }
Chris@0 737
Chris@17 738 $lines = [];
Chris@14 739
Chris@0 740 while ($this->moveToNextLine()) {
Chris@0 741 // unquoted strings end before the first unindented line
Chris@14 742 if (null === $quotation && 0 === $this->getCurrentLineIndentation()) {
Chris@0 743 $this->moveToPreviousLine();
Chris@0 744
Chris@0 745 break;
Chris@0 746 }
Chris@0 747
Chris@14 748 $lines[] = trim($this->currentLine);
Chris@0 749
Chris@0 750 // quoted string values end with a line that is terminated with the quotation character
Chris@0 751 if ('' !== $this->currentLine && substr($this->currentLine, -1) === $quotation) {
Chris@0 752 break;
Chris@0 753 }
Chris@0 754 }
Chris@0 755
Chris@17 756 for ($i = 0, $linesCount = \count($lines), $previousLineBlank = false; $i < $linesCount; ++$i) {
Chris@14 757 if ('' === $lines[$i]) {
Chris@14 758 $value .= "\n";
Chris@14 759 $previousLineBlank = true;
Chris@14 760 } elseif ($previousLineBlank) {
Chris@14 761 $value .= $lines[$i];
Chris@14 762 $previousLineBlank = false;
Chris@14 763 } else {
Chris@14 764 $value .= ' '.$lines[$i];
Chris@14 765 $previousLineBlank = false;
Chris@14 766 }
Chris@14 767 }
Chris@14 768
Chris@0 769 Inline::$parsedLineNumber = $this->getRealCurrentLineNb();
Chris@14 770
Chris@0 771 $parsedValue = Inline::parse($value, $flags, $this->refs);
Chris@0 772
Chris@17 773 if ('mapping' === $context && \is_string($parsedValue) && '"' !== $value[0] && "'" !== $value[0] && '[' !== $value[0] && '{' !== $value[0] && '!' !== $value[0] && false !== strpos($parsedValue, ': ')) {
Chris@14 774 throw new ParseException('A colon cannot be used in an unquoted mapping value.', $this->getRealCurrentLineNb() + 1, $value, $this->filename);
Chris@0 775 }
Chris@0 776
Chris@0 777 return $parsedValue;
Chris@0 778 } catch (ParseException $e) {
Chris@0 779 $e->setParsedLine($this->getRealCurrentLineNb() + 1);
Chris@0 780 $e->setSnippet($this->currentLine);
Chris@0 781
Chris@0 782 throw $e;
Chris@0 783 }
Chris@0 784 }
Chris@0 785
Chris@0 786 /**
Chris@0 787 * Parses a block scalar.
Chris@0 788 *
Chris@0 789 * @param string $style The style indicator that was used to begin this block scalar (| or >)
Chris@0 790 * @param string $chomping The chomping indicator that was used to begin this block scalar (+ or -)
Chris@0 791 * @param int $indentation The indentation indicator that was used to begin this block scalar
Chris@0 792 *
Chris@0 793 * @return string The text value
Chris@0 794 */
Chris@0 795 private function parseBlockScalar($style, $chomping = '', $indentation = 0)
Chris@0 796 {
Chris@0 797 $notEOF = $this->moveToNextLine();
Chris@0 798 if (!$notEOF) {
Chris@0 799 return '';
Chris@0 800 }
Chris@0 801
Chris@0 802 $isCurrentLineBlank = $this->isCurrentLineBlank();
Chris@17 803 $blockLines = [];
Chris@0 804
Chris@0 805 // leading blank lines are consumed before determining indentation
Chris@0 806 while ($notEOF && $isCurrentLineBlank) {
Chris@0 807 // newline only if not EOF
Chris@0 808 if ($notEOF = $this->moveToNextLine()) {
Chris@0 809 $blockLines[] = '';
Chris@0 810 $isCurrentLineBlank = $this->isCurrentLineBlank();
Chris@0 811 }
Chris@0 812 }
Chris@0 813
Chris@0 814 // determine indentation if not specified
Chris@0 815 if (0 === $indentation) {
Chris@0 816 if (self::preg_match('/^ +/', $this->currentLine, $matches)) {
Chris@17 817 $indentation = \strlen($matches[0]);
Chris@0 818 }
Chris@0 819 }
Chris@0 820
Chris@0 821 if ($indentation > 0) {
Chris@0 822 $pattern = sprintf('/^ {%d}(.*)$/', $indentation);
Chris@0 823
Chris@0 824 while (
Chris@0 825 $notEOF && (
Chris@0 826 $isCurrentLineBlank ||
Chris@0 827 self::preg_match($pattern, $this->currentLine, $matches)
Chris@0 828 )
Chris@0 829 ) {
Chris@17 830 if ($isCurrentLineBlank && \strlen($this->currentLine) > $indentation) {
Chris@0 831 $blockLines[] = substr($this->currentLine, $indentation);
Chris@0 832 } elseif ($isCurrentLineBlank) {
Chris@0 833 $blockLines[] = '';
Chris@0 834 } else {
Chris@0 835 $blockLines[] = $matches[1];
Chris@0 836 }
Chris@0 837
Chris@0 838 // newline only if not EOF
Chris@0 839 if ($notEOF = $this->moveToNextLine()) {
Chris@0 840 $isCurrentLineBlank = $this->isCurrentLineBlank();
Chris@0 841 }
Chris@0 842 }
Chris@0 843 } elseif ($notEOF) {
Chris@0 844 $blockLines[] = '';
Chris@0 845 }
Chris@0 846
Chris@0 847 if ($notEOF) {
Chris@0 848 $blockLines[] = '';
Chris@0 849 $this->moveToPreviousLine();
Chris@0 850 } elseif (!$notEOF && !$this->isCurrentLineLastLineInDocument()) {
Chris@0 851 $blockLines[] = '';
Chris@0 852 }
Chris@0 853
Chris@0 854 // folded style
Chris@0 855 if ('>' === $style) {
Chris@0 856 $text = '';
Chris@0 857 $previousLineIndented = false;
Chris@0 858 $previousLineBlank = false;
Chris@0 859
Chris@17 860 for ($i = 0, $blockLinesCount = \count($blockLines); $i < $blockLinesCount; ++$i) {
Chris@0 861 if ('' === $blockLines[$i]) {
Chris@0 862 $text .= "\n";
Chris@0 863 $previousLineIndented = false;
Chris@0 864 $previousLineBlank = true;
Chris@0 865 } elseif (' ' === $blockLines[$i][0]) {
Chris@0 866 $text .= "\n".$blockLines[$i];
Chris@0 867 $previousLineIndented = true;
Chris@0 868 $previousLineBlank = false;
Chris@0 869 } elseif ($previousLineIndented) {
Chris@0 870 $text .= "\n".$blockLines[$i];
Chris@0 871 $previousLineIndented = false;
Chris@0 872 $previousLineBlank = false;
Chris@0 873 } elseif ($previousLineBlank || 0 === $i) {
Chris@0 874 $text .= $blockLines[$i];
Chris@0 875 $previousLineIndented = false;
Chris@0 876 $previousLineBlank = false;
Chris@0 877 } else {
Chris@0 878 $text .= ' '.$blockLines[$i];
Chris@0 879 $previousLineIndented = false;
Chris@0 880 $previousLineBlank = false;
Chris@0 881 }
Chris@0 882 }
Chris@0 883 } else {
Chris@0 884 $text = implode("\n", $blockLines);
Chris@0 885 }
Chris@0 886
Chris@0 887 // deal with trailing newlines
Chris@0 888 if ('' === $chomping) {
Chris@0 889 $text = preg_replace('/\n+$/', "\n", $text);
Chris@0 890 } elseif ('-' === $chomping) {
Chris@0 891 $text = preg_replace('/\n+$/', '', $text);
Chris@0 892 }
Chris@0 893
Chris@0 894 return $text;
Chris@0 895 }
Chris@0 896
Chris@0 897 /**
Chris@0 898 * Returns true if the next line is indented.
Chris@0 899 *
Chris@0 900 * @return bool Returns true if the next line is indented, false otherwise
Chris@0 901 */
Chris@0 902 private function isNextLineIndented()
Chris@0 903 {
Chris@0 904 $currentIndentation = $this->getCurrentLineIndentation();
Chris@14 905 $movements = 0;
Chris@0 906
Chris@14 907 do {
Chris@0 908 $EOF = !$this->moveToNextLine();
Chris@14 909
Chris@14 910 if (!$EOF) {
Chris@14 911 ++$movements;
Chris@14 912 }
Chris@14 913 } while (!$EOF && ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()));
Chris@0 914
Chris@0 915 if ($EOF) {
Chris@0 916 return false;
Chris@0 917 }
Chris@0 918
Chris@0 919 $ret = $this->getCurrentLineIndentation() > $currentIndentation;
Chris@0 920
Chris@14 921 for ($i = 0; $i < $movements; ++$i) {
Chris@14 922 $this->moveToPreviousLine();
Chris@14 923 }
Chris@0 924
Chris@0 925 return $ret;
Chris@0 926 }
Chris@0 927
Chris@0 928 /**
Chris@0 929 * Returns true if the current line is blank or if it is a comment line.
Chris@0 930 *
Chris@0 931 * @return bool Returns true if the current line is empty or if it is a comment line, false otherwise
Chris@0 932 */
Chris@0 933 private function isCurrentLineEmpty()
Chris@0 934 {
Chris@0 935 return $this->isCurrentLineBlank() || $this->isCurrentLineComment();
Chris@0 936 }
Chris@0 937
Chris@0 938 /**
Chris@0 939 * Returns true if the current line is blank.
Chris@0 940 *
Chris@0 941 * @return bool Returns true if the current line is blank, false otherwise
Chris@0 942 */
Chris@0 943 private function isCurrentLineBlank()
Chris@0 944 {
Chris@0 945 return '' == trim($this->currentLine, ' ');
Chris@0 946 }
Chris@0 947
Chris@0 948 /**
Chris@0 949 * Returns true if the current line is a comment line.
Chris@0 950 *
Chris@0 951 * @return bool Returns true if the current line is a comment line, false otherwise
Chris@0 952 */
Chris@0 953 private function isCurrentLineComment()
Chris@0 954 {
Chris@0 955 //checking explicitly the first char of the trim is faster than loops or strpos
Chris@0 956 $ltrimmedLine = ltrim($this->currentLine, ' ');
Chris@0 957
Chris@14 958 return '' !== $ltrimmedLine && '#' === $ltrimmedLine[0];
Chris@0 959 }
Chris@0 960
Chris@0 961 private function isCurrentLineLastLineInDocument()
Chris@0 962 {
Chris@0 963 return ($this->offset + $this->currentLineNb) >= ($this->totalNumberOfLines - 1);
Chris@0 964 }
Chris@0 965
Chris@0 966 /**
Chris@0 967 * Cleanups a YAML string to be parsed.
Chris@0 968 *
Chris@0 969 * @param string $value The input YAML string
Chris@0 970 *
Chris@0 971 * @return string A cleaned up YAML string
Chris@0 972 */
Chris@0 973 private function cleanup($value)
Chris@0 974 {
Chris@17 975 $value = str_replace(["\r\n", "\r"], "\n", $value);
Chris@0 976
Chris@0 977 // strip YAML header
Chris@0 978 $count = 0;
Chris@0 979 $value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#u', '', $value, -1, $count);
Chris@0 980 $this->offset += $count;
Chris@0 981
Chris@0 982 // remove leading comments
Chris@0 983 $trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count);
Chris@14 984 if (1 === $count) {
Chris@0 985 // items have been removed, update the offset
Chris@0 986 $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
Chris@0 987 $value = $trimmedValue;
Chris@0 988 }
Chris@0 989
Chris@0 990 // remove start of the document marker (---)
Chris@0 991 $trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count);
Chris@14 992 if (1 === $count) {
Chris@0 993 // items have been removed, update the offset
Chris@0 994 $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
Chris@0 995 $value = $trimmedValue;
Chris@0 996
Chris@0 997 // remove end of the document marker (...)
Chris@0 998 $value = preg_replace('#\.\.\.\s*$#', '', $value);
Chris@0 999 }
Chris@0 1000
Chris@0 1001 return $value;
Chris@0 1002 }
Chris@0 1003
Chris@0 1004 /**
Chris@0 1005 * Returns true if the next line starts unindented collection.
Chris@0 1006 *
Chris@0 1007 * @return bool Returns true if the next line starts unindented collection, false otherwise
Chris@0 1008 */
Chris@0 1009 private function isNextLineUnIndentedCollection()
Chris@0 1010 {
Chris@0 1011 $currentIndentation = $this->getCurrentLineIndentation();
Chris@14 1012 $movements = 0;
Chris@0 1013
Chris@14 1014 do {
Chris@14 1015 $EOF = !$this->moveToNextLine();
Chris@0 1016
Chris@14 1017 if (!$EOF) {
Chris@14 1018 ++$movements;
Chris@14 1019 }
Chris@14 1020 } while (!$EOF && ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()));
Chris@14 1021
Chris@14 1022 if ($EOF) {
Chris@0 1023 return false;
Chris@0 1024 }
Chris@0 1025
Chris@0 1026 $ret = $this->getCurrentLineIndentation() === $currentIndentation && $this->isStringUnIndentedCollectionItem();
Chris@0 1027
Chris@14 1028 for ($i = 0; $i < $movements; ++$i) {
Chris@14 1029 $this->moveToPreviousLine();
Chris@14 1030 }
Chris@0 1031
Chris@0 1032 return $ret;
Chris@0 1033 }
Chris@0 1034
Chris@0 1035 /**
Chris@0 1036 * Returns true if the string is un-indented collection item.
Chris@0 1037 *
Chris@0 1038 * @return bool Returns true if the string is un-indented collection item, false otherwise
Chris@0 1039 */
Chris@0 1040 private function isStringUnIndentedCollectionItem()
Chris@0 1041 {
Chris@0 1042 return '-' === rtrim($this->currentLine) || 0 === strpos($this->currentLine, '- ');
Chris@0 1043 }
Chris@0 1044
Chris@0 1045 /**
Chris@0 1046 * A local wrapper for `preg_match` which will throw a ParseException if there
Chris@0 1047 * is an internal error in the PCRE engine.
Chris@0 1048 *
Chris@0 1049 * This avoids us needing to check for "false" every time PCRE is used
Chris@0 1050 * in the YAML engine
Chris@0 1051 *
Chris@0 1052 * @throws ParseException on a PCRE internal error
Chris@0 1053 *
Chris@0 1054 * @see preg_last_error()
Chris@0 1055 *
Chris@0 1056 * @internal
Chris@0 1057 */
Chris@0 1058 public static function preg_match($pattern, $subject, &$matches = null, $flags = 0, $offset = 0)
Chris@0 1059 {
Chris@0 1060 if (false === $ret = preg_match($pattern, $subject, $matches, $flags, $offset)) {
Chris@0 1061 switch (preg_last_error()) {
Chris@0 1062 case PREG_INTERNAL_ERROR:
Chris@0 1063 $error = 'Internal PCRE error.';
Chris@0 1064 break;
Chris@0 1065 case PREG_BACKTRACK_LIMIT_ERROR:
Chris@0 1066 $error = 'pcre.backtrack_limit reached.';
Chris@0 1067 break;
Chris@0 1068 case PREG_RECURSION_LIMIT_ERROR:
Chris@0 1069 $error = 'pcre.recursion_limit reached.';
Chris@0 1070 break;
Chris@0 1071 case PREG_BAD_UTF8_ERROR:
Chris@0 1072 $error = 'Malformed UTF-8 data.';
Chris@0 1073 break;
Chris@0 1074 case PREG_BAD_UTF8_OFFSET_ERROR:
Chris@0 1075 $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point.';
Chris@0 1076 break;
Chris@0 1077 default:
Chris@0 1078 $error = 'Error.';
Chris@0 1079 }
Chris@0 1080
Chris@0 1081 throw new ParseException($error);
Chris@0 1082 }
Chris@0 1083
Chris@0 1084 return $ret;
Chris@0 1085 }
Chris@14 1086
Chris@14 1087 /**
Chris@14 1088 * Trim the tag on top of the value.
Chris@14 1089 *
Chris@14 1090 * Prevent values such as `!foo {quz: bar}` to be considered as
Chris@14 1091 * a mapping block.
Chris@14 1092 */
Chris@14 1093 private function trimTag($value)
Chris@14 1094 {
Chris@14 1095 if ('!' === $value[0]) {
Chris@14 1096 return ltrim(substr($value, 1, strcspn($value, " \r\n", 1)), ' ');
Chris@14 1097 }
Chris@14 1098
Chris@14 1099 return $value;
Chris@14 1100 }
Chris@14 1101
Chris@14 1102 private function getLineTag($value, $flags, $nextLineCheck = true)
Chris@14 1103 {
Chris@14 1104 if ('' === $value || '!' !== $value[0] || 1 !== self::preg_match('/^'.self::TAG_PATTERN.' *( +#.*)?$/', $value, $matches)) {
Chris@14 1105 return;
Chris@14 1106 }
Chris@14 1107
Chris@14 1108 if ($nextLineCheck && !$this->isNextLineIndented()) {
Chris@14 1109 return;
Chris@14 1110 }
Chris@14 1111
Chris@14 1112 $tag = substr($matches['tag'], 1);
Chris@14 1113
Chris@14 1114 // Built-in tags
Chris@14 1115 if ($tag && '!' === $tag[0]) {
Chris@14 1116 throw new ParseException(sprintf('The built-in tag "!%s" is not implemented.', $tag), $this->getRealCurrentLineNb() + 1, $value, $this->filename);
Chris@14 1117 }
Chris@14 1118
Chris@14 1119 if (Yaml::PARSE_CUSTOM_TAGS & $flags) {
Chris@14 1120 return $tag;
Chris@14 1121 }
Chris@14 1122
Chris@14 1123 throw new ParseException(sprintf('Tags support is not enabled. You must use the flag `Yaml::PARSE_CUSTOM_TAGS` to use "%s".', $matches['tag']), $this->getRealCurrentLineNb() + 1, $value, $this->filename);
Chris@14 1124 }
Chris@14 1125
Chris@14 1126 private function getDeprecationMessage($message)
Chris@14 1127 {
Chris@14 1128 $message = rtrim($message, '.');
Chris@14 1129
Chris@14 1130 if (null !== $this->filename) {
Chris@14 1131 $message .= ' in '.$this->filename;
Chris@14 1132 }
Chris@14 1133
Chris@14 1134 $message .= ' on line '.($this->getRealCurrentLineNb() + 1);
Chris@14 1135
Chris@14 1136 return $message.'.';
Chris@14 1137 }
Chris@0 1138 }