Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Symfony\Component\Yaml; Chris@0: Chris@0: use Symfony\Component\Yaml\Exception\ParseException; Chris@0: Chris@0: /** Chris@0: * Parser parses YAML strings to convert them to PHP arrays. Chris@0: * Chris@0: * @author Fabien Potencier Chris@0: */ Chris@0: class Parser Chris@0: { Chris@0: const TAG_PATTERN = '((?P![\w!.\/:-]+) +)?'; Chris@0: const BLOCK_SCALAR_HEADER_PATTERN = '(?P\||>)(?P\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P +#.*)?'; Chris@0: Chris@0: private $offset = 0; Chris@0: private $totalNumberOfLines; Chris@0: private $lines = array(); Chris@0: private $currentLineNb = -1; Chris@0: private $currentLine = ''; Chris@0: private $refs = array(); Chris@0: private $skippedLineNumbers = array(); Chris@0: private $locallySkippedLineNumbers = array(); Chris@0: Chris@0: /** Chris@0: * Constructor. Chris@0: * Chris@0: * @param int $offset The offset of YAML document (used for line numbers in error messages) Chris@0: * @param int|null $totalNumberOfLines The overall number of lines being parsed Chris@0: * @param int[] $skippedLineNumbers Number of comment lines that have been skipped by the parser Chris@0: */ Chris@0: public function __construct($offset = 0, $totalNumberOfLines = null, array $skippedLineNumbers = array()) Chris@0: { Chris@0: $this->offset = $offset; Chris@0: $this->totalNumberOfLines = $totalNumberOfLines; Chris@0: $this->skippedLineNumbers = $skippedLineNumbers; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Parses a YAML string to a PHP value. Chris@0: * Chris@0: * @param string $value A YAML string Chris@0: * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior Chris@0: * Chris@0: * @return mixed A PHP value Chris@0: * Chris@0: * @throws ParseException If the YAML is not valid Chris@0: */ Chris@0: public function parse($value, $flags = 0) Chris@0: { Chris@0: if (is_bool($flags)) { Chris@0: @trigger_error('Passing a boolean flag to toggle exception handling is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED); Chris@0: Chris@0: if ($flags) { Chris@0: $flags = Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE; Chris@0: } else { Chris@0: $flags = 0; Chris@0: } Chris@0: } Chris@0: Chris@0: if (func_num_args() >= 3) { Chris@0: @trigger_error('Passing a boolean flag to toggle object support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT flag instead.', E_USER_DEPRECATED); Chris@0: Chris@0: if (func_get_arg(2)) { Chris@0: $flags |= Yaml::PARSE_OBJECT; Chris@0: } Chris@0: } Chris@0: Chris@0: if (func_num_args() >= 4) { Chris@0: @trigger_error('Passing a boolean flag to toggle object for map support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT_FOR_MAP flag instead.', E_USER_DEPRECATED); Chris@0: Chris@0: if (func_get_arg(3)) { Chris@0: $flags |= Yaml::PARSE_OBJECT_FOR_MAP; Chris@0: } Chris@0: } Chris@0: Chris@0: if (false === preg_match('//u', $value)) { Chris@0: throw new ParseException('The YAML value does not appear to be valid UTF-8.'); Chris@0: } Chris@0: Chris@0: $this->refs = array(); Chris@0: Chris@0: $mbEncoding = null; Chris@0: $e = null; Chris@0: $data = null; Chris@0: Chris@0: if (2 /* MB_OVERLOAD_STRING */ & (int) ini_get('mbstring.func_overload')) { Chris@0: $mbEncoding = mb_internal_encoding(); Chris@0: mb_internal_encoding('UTF-8'); Chris@0: } Chris@0: Chris@0: try { Chris@0: $data = $this->doParse($value, $flags); Chris@0: } catch (\Exception $e) { Chris@0: } catch (\Throwable $e) { Chris@0: } Chris@0: Chris@0: if (null !== $mbEncoding) { Chris@0: mb_internal_encoding($mbEncoding); Chris@0: } Chris@0: Chris@0: $this->lines = array(); Chris@0: $this->currentLine = ''; Chris@0: $this->refs = array(); Chris@0: $this->skippedLineNumbers = array(); Chris@0: $this->locallySkippedLineNumbers = array(); Chris@0: Chris@0: if (null !== $e) { Chris@0: throw $e; Chris@0: } Chris@0: Chris@0: return $data; Chris@0: } Chris@0: Chris@0: private function doParse($value, $flags) Chris@0: { Chris@0: $this->currentLineNb = -1; Chris@0: $this->currentLine = ''; Chris@0: $value = $this->cleanup($value); Chris@0: $this->lines = explode("\n", $value); Chris@0: $this->locallySkippedLineNumbers = array(); Chris@0: Chris@0: if (null === $this->totalNumberOfLines) { Chris@0: $this->totalNumberOfLines = count($this->lines); Chris@0: } Chris@0: Chris@0: $data = array(); Chris@0: $context = null; Chris@0: $allowOverwrite = false; Chris@0: Chris@0: while ($this->moveToNextLine()) { Chris@0: if ($this->isCurrentLineEmpty()) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: // tab? Chris@0: if ("\t" === $this->currentLine[0]) { Chris@0: throw new ParseException('A YAML file cannot contain tabs as indentation.', $this->getRealCurrentLineNb() + 1, $this->currentLine); Chris@0: } Chris@0: Chris@0: $isRef = $mergeNode = false; Chris@0: if (self::preg_match('#^\-((?P\s+)(?P.+))?$#u', rtrim($this->currentLine), $values)) { Chris@0: if ($context && 'mapping' == $context) { Chris@0: throw new ParseException('You cannot define a sequence item when in a mapping', $this->getRealCurrentLineNb() + 1, $this->currentLine); Chris@0: } Chris@0: $context = 'sequence'; Chris@0: Chris@0: if (isset($values['value']) && self::preg_match('#^&(?P[^ ]+) *(?P.*)#u', $values['value'], $matches)) { Chris@0: $isRef = $matches['ref']; Chris@0: $values['value'] = $matches['value']; Chris@0: } Chris@0: Chris@0: // array Chris@0: if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) { Chris@0: $data[] = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(null, true), $flags); Chris@0: } else { Chris@0: if (isset($values['leadspaces']) Chris@0: && self::preg_match('#^(?P'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{\[].*?) *\:(\s+(?P.+))?$#u', rtrim($values['value']), $matches) Chris@0: ) { Chris@0: // this is a compact notation element, add to next block and parse Chris@0: $block = $values['value']; Chris@0: if ($this->isNextLineIndented()) { Chris@0: $block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + strlen($values['leadspaces']) + 1); Chris@0: } Chris@0: Chris@0: $data[] = $this->parseBlock($this->getRealCurrentLineNb(), $block, $flags); Chris@0: } else { Chris@0: $data[] = $this->parseValue($values['value'], $flags, $context); Chris@0: } Chris@0: } Chris@0: if ($isRef) { Chris@0: $this->refs[$isRef] = end($data); Chris@0: } Chris@0: } elseif ( Chris@0: self::preg_match('#^(?P'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\[\{].*?) *\:(\s+(?P.+))?$#u', rtrim($this->currentLine), $values) Chris@0: && (false === strpos($values['key'], ' #') || in_array($values['key'][0], array('"', "'"))) Chris@0: ) { Chris@0: if ($context && 'sequence' == $context) { Chris@0: throw new ParseException('You cannot define a mapping item when in a sequence', $this->currentLineNb + 1, $this->currentLine); Chris@0: } Chris@0: $context = 'mapping'; Chris@0: Chris@0: // force correct settings Chris@0: Inline::parse(null, $flags, $this->refs); Chris@0: try { Chris@0: Inline::$parsedLineNumber = $this->getRealCurrentLineNb(); Chris@0: $key = Inline::parseScalar($values['key']); Chris@0: } catch (ParseException $e) { Chris@0: $e->setParsedLine($this->getRealCurrentLineNb() + 1); Chris@0: $e->setSnippet($this->currentLine); Chris@0: Chris@0: throw $e; Chris@0: } Chris@0: Chris@0: // Convert float keys to strings, to avoid being converted to integers by PHP Chris@0: if (is_float($key)) { Chris@0: $key = (string) $key; Chris@0: } Chris@0: Chris@0: if ('<<' === $key) { Chris@0: $mergeNode = true; Chris@0: $allowOverwrite = true; Chris@0: if (isset($values['value']) && 0 === strpos($values['value'], '*')) { Chris@0: $refName = substr($values['value'], 1); Chris@0: if (!array_key_exists($refName, $this->refs)) { Chris@0: throw new ParseException(sprintf('Reference "%s" does not exist.', $refName), $this->getRealCurrentLineNb() + 1, $this->currentLine); Chris@0: } Chris@0: Chris@0: $refValue = $this->refs[$refName]; Chris@0: Chris@0: if (!is_array($refValue)) { Chris@0: throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine); Chris@0: } Chris@0: Chris@0: $data += $refValue; // array union Chris@0: } else { Chris@0: if (isset($values['value']) && $values['value'] !== '') { Chris@0: $value = $values['value']; Chris@0: } else { Chris@0: $value = $this->getNextEmbedBlock(); Chris@0: } Chris@0: $parsed = $this->parseBlock($this->getRealCurrentLineNb() + 1, $value, $flags); Chris@0: Chris@0: if (!is_array($parsed)) { Chris@0: throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine); Chris@0: } Chris@0: Chris@0: if (isset($parsed[0])) { Chris@0: // If the value associated with the merge key is a sequence, then this sequence is expected to contain mapping nodes Chris@0: // and each of these nodes is merged in turn according to its order in the sequence. Keys in mapping nodes earlier Chris@0: // in the sequence override keys specified in later mapping nodes. Chris@0: foreach ($parsed as $parsedItem) { Chris@0: if (!is_array($parsedItem)) { Chris@0: throw new ParseException('Merge items must be arrays.', $this->getRealCurrentLineNb() + 1, $parsedItem); Chris@0: } Chris@0: Chris@0: $data += $parsedItem; // array union Chris@0: } Chris@0: } else { Chris@0: // If the value associated with the key is a single mapping node, each of its key/value pairs is inserted into the Chris@0: // current mapping, unless the key already exists in it. Chris@0: $data += $parsed; // array union Chris@0: } Chris@0: } Chris@0: } elseif (isset($values['value']) && self::preg_match('#^&(?P[^ ]+) *(?P.*)#u', $values['value'], $matches)) { Chris@0: $isRef = $matches['ref']; Chris@0: $values['value'] = $matches['value']; Chris@0: } Chris@0: Chris@0: if ($mergeNode) { Chris@0: // Merge keys Chris@0: } elseif (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) { Chris@0: // hash Chris@0: // if next line is less indented or equal, then it means that the current value is null Chris@0: if (!$this->isNextLineIndented() && !$this->isNextLineUnIndentedCollection()) { Chris@0: // Spec: Keys MUST be unique; first one wins. Chris@0: // But overwriting is allowed when a merge node is used in current block. Chris@0: if ($allowOverwrite || !isset($data[$key])) { Chris@0: $data[$key] = null; Chris@0: } else { Chris@0: @trigger_error(sprintf('Duplicate key "%s" detected on line %d whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated since version 3.2 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.', $key, $this->getRealCurrentLineNb() + 1), E_USER_DEPRECATED); Chris@0: } Chris@0: } else { Chris@0: // remember the parsed line number here in case we need it to provide some contexts in error messages below Chris@0: $realCurrentLineNbKey = $this->getRealCurrentLineNb(); Chris@0: $value = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(), $flags); Chris@0: // Spec: Keys MUST be unique; first one wins. Chris@0: // But overwriting is allowed when a merge node is used in current block. Chris@0: if ($allowOverwrite || !isset($data[$key])) { Chris@0: $data[$key] = $value; Chris@0: } else { Chris@0: @trigger_error(sprintf('Duplicate key "%s" detected on line %d whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated since version 3.2 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.', $key, $realCurrentLineNbKey + 1), E_USER_DEPRECATED); Chris@0: } Chris@0: } Chris@0: } else { Chris@0: $value = $this->parseValue($values['value'], $flags, $context); Chris@0: // Spec: Keys MUST be unique; first one wins. Chris@0: // But overwriting is allowed when a merge node is used in current block. Chris@0: if ($allowOverwrite || !isset($data[$key])) { Chris@0: $data[$key] = $value; Chris@0: } else { Chris@0: @trigger_error(sprintf('Duplicate key "%s" detected on line %d whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated since version 3.2 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.', $key, $this->getRealCurrentLineNb() + 1), E_USER_DEPRECATED); Chris@0: } Chris@0: } Chris@0: if ($isRef) { Chris@0: $this->refs[$isRef] = $data[$key]; Chris@0: } Chris@0: } else { Chris@0: // multiple documents are not supported Chris@0: if ('---' === $this->currentLine) { Chris@0: throw new ParseException('Multiple documents are not supported.', $this->currentLineNb + 1, $this->currentLine); Chris@0: } Chris@0: Chris@0: // 1-liner optionally followed by newline(s) Chris@0: if (is_string($value) && $this->lines[0] === trim($value)) { Chris@0: try { Chris@0: Inline::$parsedLineNumber = $this->getRealCurrentLineNb(); Chris@0: $value = Inline::parse($this->lines[0], $flags, $this->refs); Chris@0: } catch (ParseException $e) { Chris@0: $e->setParsedLine($this->getRealCurrentLineNb() + 1); Chris@0: $e->setSnippet($this->currentLine); Chris@0: Chris@0: throw $e; Chris@0: } Chris@0: Chris@0: return $value; Chris@0: } Chris@0: Chris@0: throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine); Chris@0: } Chris@0: } Chris@0: Chris@0: if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && !is_object($data) && 'mapping' === $context) { Chris@0: $object = new \stdClass(); Chris@0: Chris@0: foreach ($data as $key => $value) { Chris@0: $object->$key = $value; Chris@0: } Chris@0: Chris@0: $data = $object; Chris@0: } Chris@0: Chris@0: return empty($data) ? null : $data; Chris@0: } Chris@0: Chris@0: private function parseBlock($offset, $yaml, $flags) Chris@0: { Chris@0: $skippedLineNumbers = $this->skippedLineNumbers; Chris@0: Chris@0: foreach ($this->locallySkippedLineNumbers as $lineNumber) { Chris@0: if ($lineNumber < $offset) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: $skippedLineNumbers[] = $lineNumber; Chris@0: } Chris@0: Chris@0: $parser = new self($offset, $this->totalNumberOfLines, $skippedLineNumbers); Chris@0: $parser->refs = &$this->refs; Chris@0: Chris@0: return $parser->doParse($yaml, $flags); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the current line number (takes the offset into account). Chris@0: * Chris@0: * @return int The current line number Chris@0: */ Chris@0: private function getRealCurrentLineNb() Chris@0: { Chris@0: $realCurrentLineNumber = $this->currentLineNb + $this->offset; Chris@0: Chris@0: foreach ($this->skippedLineNumbers as $skippedLineNumber) { Chris@0: if ($skippedLineNumber > $realCurrentLineNumber) { Chris@0: break; Chris@0: } Chris@0: Chris@0: ++$realCurrentLineNumber; Chris@0: } Chris@0: Chris@0: return $realCurrentLineNumber; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the current line indentation. Chris@0: * Chris@0: * @return int The current line indentation Chris@0: */ Chris@0: private function getCurrentLineIndentation() Chris@0: { Chris@0: return strlen($this->currentLine) - strlen(ltrim($this->currentLine, ' ')); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the next embed block of YAML. Chris@0: * Chris@0: * @param int $indentation The indent level at which the block is to be read, or null for default Chris@0: * @param bool $inSequence True if the enclosing data structure is a sequence Chris@0: * Chris@0: * @return string A YAML string Chris@0: * Chris@0: * @throws ParseException When indentation problem are detected Chris@0: */ Chris@0: private function getNextEmbedBlock($indentation = null, $inSequence = false) Chris@0: { Chris@0: $oldLineIndentation = $this->getCurrentLineIndentation(); Chris@0: $blockScalarIndentations = array(); Chris@0: Chris@0: if ($this->isBlockScalarHeader()) { Chris@0: $blockScalarIndentations[] = $this->getCurrentLineIndentation(); Chris@0: } Chris@0: Chris@0: if (!$this->moveToNextLine()) { Chris@0: return; Chris@0: } Chris@0: Chris@0: if (null === $indentation) { Chris@0: $newIndent = $this->getCurrentLineIndentation(); Chris@0: Chris@0: $unindentedEmbedBlock = $this->isStringUnIndentedCollectionItem(); Chris@0: Chris@0: if (!$this->isCurrentLineEmpty() && 0 === $newIndent && !$unindentedEmbedBlock) { Chris@0: throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine); Chris@0: } Chris@0: } else { Chris@0: $newIndent = $indentation; Chris@0: } Chris@0: Chris@0: $data = array(); Chris@0: if ($this->getCurrentLineIndentation() >= $newIndent) { Chris@0: $data[] = substr($this->currentLine, $newIndent); Chris@0: } else { Chris@0: $this->moveToPreviousLine(); Chris@0: Chris@0: return; Chris@0: } Chris@0: Chris@0: if ($inSequence && $oldLineIndentation === $newIndent && isset($data[0][0]) && '-' === $data[0][0]) { Chris@0: // the previous line contained a dash but no item content, this line is a sequence item with the same indentation Chris@0: // and therefore no nested list or mapping Chris@0: $this->moveToPreviousLine(); Chris@0: Chris@0: return; Chris@0: } Chris@0: Chris@0: $isItUnindentedCollection = $this->isStringUnIndentedCollectionItem(); Chris@0: Chris@0: if (empty($blockScalarIndentations) && $this->isBlockScalarHeader()) { Chris@0: $blockScalarIndentations[] = $this->getCurrentLineIndentation(); Chris@0: } Chris@0: Chris@0: $previousLineIndentation = $this->getCurrentLineIndentation(); Chris@0: Chris@0: while ($this->moveToNextLine()) { Chris@0: $indent = $this->getCurrentLineIndentation(); Chris@0: Chris@0: // terminate all block scalars that are more indented than the current line Chris@0: if (!empty($blockScalarIndentations) && $indent < $previousLineIndentation && trim($this->currentLine) !== '') { Chris@0: foreach ($blockScalarIndentations as $key => $blockScalarIndentation) { Chris@0: if ($blockScalarIndentation >= $this->getCurrentLineIndentation()) { Chris@0: unset($blockScalarIndentations[$key]); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: if (empty($blockScalarIndentations) && !$this->isCurrentLineComment() && $this->isBlockScalarHeader()) { Chris@0: $blockScalarIndentations[] = $this->getCurrentLineIndentation(); Chris@0: } Chris@0: Chris@0: $previousLineIndentation = $indent; Chris@0: Chris@0: if ($isItUnindentedCollection && !$this->isCurrentLineEmpty() && !$this->isStringUnIndentedCollectionItem() && $newIndent === $indent) { Chris@0: $this->moveToPreviousLine(); Chris@0: break; Chris@0: } Chris@0: Chris@0: if ($this->isCurrentLineBlank()) { Chris@0: $data[] = substr($this->currentLine, $newIndent); Chris@0: continue; Chris@0: } Chris@0: Chris@0: // we ignore "comment" lines only when we are not inside a scalar block Chris@0: if (empty($blockScalarIndentations) && $this->isCurrentLineComment()) { Chris@0: // remember ignored comment lines (they are used later in nested Chris@0: // parser calls to determine real line numbers) Chris@0: // Chris@0: // CAUTION: beware to not populate the global property here as it Chris@0: // will otherwise influence the getRealCurrentLineNb() call here Chris@0: // for consecutive comment lines and subsequent embedded blocks Chris@0: $this->locallySkippedLineNumbers[] = $this->getRealCurrentLineNb(); Chris@0: Chris@0: continue; Chris@0: } Chris@0: Chris@0: if ($indent >= $newIndent) { Chris@0: $data[] = substr($this->currentLine, $newIndent); Chris@0: } elseif (0 == $indent) { Chris@0: $this->moveToPreviousLine(); Chris@0: Chris@0: break; Chris@0: } else { Chris@0: throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine); Chris@0: } Chris@0: } Chris@0: Chris@0: return implode("\n", $data); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Moves the parser to the next line. Chris@0: * Chris@0: * @return bool Chris@0: */ Chris@0: private function moveToNextLine() Chris@0: { Chris@0: if ($this->currentLineNb >= count($this->lines) - 1) { Chris@0: return false; Chris@0: } Chris@0: Chris@0: $this->currentLine = $this->lines[++$this->currentLineNb]; Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Moves the parser to the previous line. Chris@0: * Chris@0: * @return bool Chris@0: */ Chris@0: private function moveToPreviousLine() Chris@0: { Chris@0: if ($this->currentLineNb < 1) { Chris@0: return false; Chris@0: } Chris@0: Chris@0: $this->currentLine = $this->lines[--$this->currentLineNb]; Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Parses a YAML value. Chris@0: * Chris@0: * @param string $value A YAML value Chris@0: * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior Chris@0: * @param string $context The parser context (either sequence or mapping) Chris@0: * Chris@0: * @return mixed A PHP value Chris@0: * Chris@0: * @throws ParseException When reference does not exist Chris@0: */ Chris@0: private function parseValue($value, $flags, $context) Chris@0: { Chris@0: if (0 === strpos($value, '*')) { Chris@0: if (false !== $pos = strpos($value, '#')) { Chris@0: $value = substr($value, 1, $pos - 2); Chris@0: } else { Chris@0: $value = substr($value, 1); Chris@0: } Chris@0: Chris@0: if (!array_key_exists($value, $this->refs)) { Chris@0: throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLineNb + 1, $this->currentLine); Chris@0: } Chris@0: Chris@0: return $this->refs[$value]; Chris@0: } Chris@0: Chris@0: if (self::preg_match('/^'.self::TAG_PATTERN.self::BLOCK_SCALAR_HEADER_PATTERN.'$/', $value, $matches)) { Chris@0: $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : ''; Chris@0: Chris@0: $data = $this->parseBlockScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), (int) abs($modifiers)); Chris@0: Chris@0: if (isset($matches['tag']) && '!!binary' === $matches['tag']) { Chris@0: return Inline::evaluateBinaryScalar($data); Chris@0: } Chris@0: Chris@0: return $data; Chris@0: } Chris@0: Chris@0: try { Chris@0: $quotation = '' !== $value && ('"' === $value[0] || "'" === $value[0]) ? $value[0] : null; Chris@0: Chris@0: // do not take following lines into account when the current line is a quoted single line value Chris@0: if (null !== $quotation && preg_match('/^'.$quotation.'.*'.$quotation.'(\s*#.*)?$/', $value)) { Chris@0: return Inline::parse($value, $flags, $this->refs); Chris@0: } Chris@0: Chris@0: while ($this->moveToNextLine()) { Chris@0: // unquoted strings end before the first unindented line Chris@0: if (null === $quotation && $this->getCurrentLineIndentation() === 0) { Chris@0: $this->moveToPreviousLine(); Chris@0: Chris@0: break; Chris@0: } Chris@0: Chris@0: $value .= ' '.trim($this->currentLine); Chris@0: Chris@0: // quoted string values end with a line that is terminated with the quotation character Chris@0: if ('' !== $this->currentLine && substr($this->currentLine, -1) === $quotation) { Chris@0: break; Chris@0: } Chris@0: } Chris@0: Chris@0: Inline::$parsedLineNumber = $this->getRealCurrentLineNb(); Chris@0: $parsedValue = Inline::parse($value, $flags, $this->refs); Chris@0: Chris@0: if ('mapping' === $context && is_string($parsedValue) && '"' !== $value[0] && "'" !== $value[0] && '[' !== $value[0] && '{' !== $value[0] && '!' !== $value[0] && false !== strpos($parsedValue, ': ')) { Chris@0: throw new ParseException('A colon cannot be used in an unquoted mapping value.'); Chris@0: } Chris@0: Chris@0: return $parsedValue; Chris@0: } catch (ParseException $e) { Chris@0: $e->setParsedLine($this->getRealCurrentLineNb() + 1); Chris@0: $e->setSnippet($this->currentLine); Chris@0: Chris@0: throw $e; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Parses a block scalar. Chris@0: * Chris@0: * @param string $style The style indicator that was used to begin this block scalar (| or >) Chris@0: * @param string $chomping The chomping indicator that was used to begin this block scalar (+ or -) Chris@0: * @param int $indentation The indentation indicator that was used to begin this block scalar Chris@0: * Chris@0: * @return string The text value Chris@0: */ Chris@0: private function parseBlockScalar($style, $chomping = '', $indentation = 0) Chris@0: { Chris@0: $notEOF = $this->moveToNextLine(); Chris@0: if (!$notEOF) { Chris@0: return ''; Chris@0: } Chris@0: Chris@0: $isCurrentLineBlank = $this->isCurrentLineBlank(); Chris@0: $blockLines = array(); Chris@0: Chris@0: // leading blank lines are consumed before determining indentation Chris@0: while ($notEOF && $isCurrentLineBlank) { Chris@0: // newline only if not EOF Chris@0: if ($notEOF = $this->moveToNextLine()) { Chris@0: $blockLines[] = ''; Chris@0: $isCurrentLineBlank = $this->isCurrentLineBlank(); Chris@0: } Chris@0: } Chris@0: Chris@0: // determine indentation if not specified Chris@0: if (0 === $indentation) { Chris@0: if (self::preg_match('/^ +/', $this->currentLine, $matches)) { Chris@0: $indentation = strlen($matches[0]); Chris@0: } Chris@0: } Chris@0: Chris@0: if ($indentation > 0) { Chris@0: $pattern = sprintf('/^ {%d}(.*)$/', $indentation); Chris@0: Chris@0: while ( Chris@0: $notEOF && ( Chris@0: $isCurrentLineBlank || Chris@0: self::preg_match($pattern, $this->currentLine, $matches) Chris@0: ) Chris@0: ) { Chris@0: if ($isCurrentLineBlank && strlen($this->currentLine) > $indentation) { Chris@0: $blockLines[] = substr($this->currentLine, $indentation); Chris@0: } elseif ($isCurrentLineBlank) { Chris@0: $blockLines[] = ''; Chris@0: } else { Chris@0: $blockLines[] = $matches[1]; Chris@0: } Chris@0: Chris@0: // newline only if not EOF Chris@0: if ($notEOF = $this->moveToNextLine()) { Chris@0: $isCurrentLineBlank = $this->isCurrentLineBlank(); Chris@0: } Chris@0: } Chris@0: } elseif ($notEOF) { Chris@0: $blockLines[] = ''; Chris@0: } Chris@0: Chris@0: if ($notEOF) { Chris@0: $blockLines[] = ''; Chris@0: $this->moveToPreviousLine(); Chris@0: } elseif (!$notEOF && !$this->isCurrentLineLastLineInDocument()) { Chris@0: $blockLines[] = ''; Chris@0: } Chris@0: Chris@0: // folded style Chris@0: if ('>' === $style) { Chris@0: $text = ''; Chris@0: $previousLineIndented = false; Chris@0: $previousLineBlank = false; Chris@0: Chris@0: for ($i = 0, $blockLinesCount = count($blockLines); $i < $blockLinesCount; ++$i) { Chris@0: if ('' === $blockLines[$i]) { Chris@0: $text .= "\n"; Chris@0: $previousLineIndented = false; Chris@0: $previousLineBlank = true; Chris@0: } elseif (' ' === $blockLines[$i][0]) { Chris@0: $text .= "\n".$blockLines[$i]; Chris@0: $previousLineIndented = true; Chris@0: $previousLineBlank = false; Chris@0: } elseif ($previousLineIndented) { Chris@0: $text .= "\n".$blockLines[$i]; Chris@0: $previousLineIndented = false; Chris@0: $previousLineBlank = false; Chris@0: } elseif ($previousLineBlank || 0 === $i) { Chris@0: $text .= $blockLines[$i]; Chris@0: $previousLineIndented = false; Chris@0: $previousLineBlank = false; Chris@0: } else { Chris@0: $text .= ' '.$blockLines[$i]; Chris@0: $previousLineIndented = false; Chris@0: $previousLineBlank = false; Chris@0: } Chris@0: } Chris@0: } else { Chris@0: $text = implode("\n", $blockLines); Chris@0: } Chris@0: Chris@0: // deal with trailing newlines Chris@0: if ('' === $chomping) { Chris@0: $text = preg_replace('/\n+$/', "\n", $text); Chris@0: } elseif ('-' === $chomping) { Chris@0: $text = preg_replace('/\n+$/', '', $text); Chris@0: } Chris@0: Chris@0: return $text; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns true if the next line is indented. Chris@0: * Chris@0: * @return bool Returns true if the next line is indented, false otherwise Chris@0: */ Chris@0: private function isNextLineIndented() Chris@0: { Chris@0: $currentIndentation = $this->getCurrentLineIndentation(); Chris@0: $EOF = !$this->moveToNextLine(); Chris@0: Chris@0: while (!$EOF && $this->isCurrentLineEmpty()) { Chris@0: $EOF = !$this->moveToNextLine(); Chris@0: } Chris@0: Chris@0: if ($EOF) { Chris@0: return false; Chris@0: } Chris@0: Chris@0: $ret = $this->getCurrentLineIndentation() > $currentIndentation; Chris@0: Chris@0: $this->moveToPreviousLine(); Chris@0: Chris@0: return $ret; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns true if the current line is blank or if it is a comment line. Chris@0: * Chris@0: * @return bool Returns true if the current line is empty or if it is a comment line, false otherwise Chris@0: */ Chris@0: private function isCurrentLineEmpty() Chris@0: { Chris@0: return $this->isCurrentLineBlank() || $this->isCurrentLineComment(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns true if the current line is blank. Chris@0: * Chris@0: * @return bool Returns true if the current line is blank, false otherwise Chris@0: */ Chris@0: private function isCurrentLineBlank() Chris@0: { Chris@0: return '' == trim($this->currentLine, ' '); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns true if the current line is a comment line. Chris@0: * Chris@0: * @return bool Returns true if the current line is a comment line, false otherwise Chris@0: */ Chris@0: private function isCurrentLineComment() Chris@0: { Chris@0: //checking explicitly the first char of the trim is faster than loops or strpos Chris@0: $ltrimmedLine = ltrim($this->currentLine, ' '); Chris@0: Chris@0: return '' !== $ltrimmedLine && $ltrimmedLine[0] === '#'; Chris@0: } Chris@0: Chris@0: private function isCurrentLineLastLineInDocument() Chris@0: { Chris@0: return ($this->offset + $this->currentLineNb) >= ($this->totalNumberOfLines - 1); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Cleanups a YAML string to be parsed. Chris@0: * Chris@0: * @param string $value The input YAML string Chris@0: * Chris@0: * @return string A cleaned up YAML string Chris@0: */ Chris@0: private function cleanup($value) Chris@0: { Chris@0: $value = str_replace(array("\r\n", "\r"), "\n", $value); Chris@0: Chris@0: // strip YAML header Chris@0: $count = 0; Chris@0: $value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#u', '', $value, -1, $count); Chris@0: $this->offset += $count; Chris@0: Chris@0: // remove leading comments Chris@0: $trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count); Chris@0: if ($count == 1) { Chris@0: // items have been removed, update the offset Chris@0: $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n"); Chris@0: $value = $trimmedValue; Chris@0: } Chris@0: Chris@0: // remove start of the document marker (---) Chris@0: $trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count); Chris@0: if ($count == 1) { Chris@0: // items have been removed, update the offset Chris@0: $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n"); Chris@0: $value = $trimmedValue; Chris@0: Chris@0: // remove end of the document marker (...) Chris@0: $value = preg_replace('#\.\.\.\s*$#', '', $value); Chris@0: } Chris@0: Chris@0: return $value; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns true if the next line starts unindented collection. Chris@0: * Chris@0: * @return bool Returns true if the next line starts unindented collection, false otherwise Chris@0: */ Chris@0: private function isNextLineUnIndentedCollection() Chris@0: { Chris@0: $currentIndentation = $this->getCurrentLineIndentation(); Chris@0: $notEOF = $this->moveToNextLine(); Chris@0: Chris@0: while ($notEOF && $this->isCurrentLineEmpty()) { Chris@0: $notEOF = $this->moveToNextLine(); Chris@0: } Chris@0: Chris@0: if (false === $notEOF) { Chris@0: return false; Chris@0: } Chris@0: Chris@0: $ret = $this->getCurrentLineIndentation() === $currentIndentation && $this->isStringUnIndentedCollectionItem(); Chris@0: Chris@0: $this->moveToPreviousLine(); Chris@0: Chris@0: return $ret; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns true if the string is un-indented collection item. Chris@0: * Chris@0: * @return bool Returns true if the string is un-indented collection item, false otherwise Chris@0: */ Chris@0: private function isStringUnIndentedCollectionItem() Chris@0: { Chris@0: return '-' === rtrim($this->currentLine) || 0 === strpos($this->currentLine, '- '); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Tests whether or not the current line is the header of a block scalar. Chris@0: * Chris@0: * @return bool Chris@0: */ Chris@0: private function isBlockScalarHeader() Chris@0: { Chris@0: return (bool) self::preg_match('~'.self::BLOCK_SCALAR_HEADER_PATTERN.'$~', $this->currentLine); Chris@0: } Chris@0: Chris@0: /** Chris@0: * A local wrapper for `preg_match` which will throw a ParseException if there Chris@0: * is an internal error in the PCRE engine. Chris@0: * Chris@0: * This avoids us needing to check for "false" every time PCRE is used Chris@0: * in the YAML engine Chris@0: * Chris@0: * @throws ParseException on a PCRE internal error Chris@0: * Chris@0: * @see preg_last_error() Chris@0: * Chris@0: * @internal Chris@0: */ Chris@0: public static function preg_match($pattern, $subject, &$matches = null, $flags = 0, $offset = 0) Chris@0: { Chris@0: if (false === $ret = preg_match($pattern, $subject, $matches, $flags, $offset)) { Chris@0: switch (preg_last_error()) { Chris@0: case PREG_INTERNAL_ERROR: Chris@0: $error = 'Internal PCRE error.'; Chris@0: break; Chris@0: case PREG_BACKTRACK_LIMIT_ERROR: Chris@0: $error = 'pcre.backtrack_limit reached.'; Chris@0: break; Chris@0: case PREG_RECURSION_LIMIT_ERROR: Chris@0: $error = 'pcre.recursion_limit reached.'; Chris@0: break; Chris@0: case PREG_BAD_UTF8_ERROR: Chris@0: $error = 'Malformed UTF-8 data.'; Chris@0: break; Chris@0: case PREG_BAD_UTF8_OFFSET_ERROR: Chris@0: $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point.'; Chris@0: break; Chris@0: default: Chris@0: $error = 'Error.'; Chris@0: } Chris@0: Chris@0: throw new ParseException($error); Chris@0: } Chris@0: Chris@0: return $ret; Chris@0: } Chris@0: }