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@17: use Symfony\Component\Yaml\Exception\DumpException; Chris@0: use Symfony\Component\Yaml\Exception\ParseException; Chris@14: use Symfony\Component\Yaml\Tag\TaggedValue; Chris@0: Chris@0: /** Chris@0: * Inline implements a YAML parser/dumper for the YAML inline syntax. Chris@0: * Chris@0: * @author Fabien Potencier Chris@0: * Chris@0: * @internal Chris@0: */ Chris@0: class Inline Chris@0: { Chris@0: const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*+(?:\\\\.[^"\\\\]*+)*+)"|\'([^\']*+(?:\'\'[^\']*+)*+)\')'; Chris@0: Chris@14: public static $parsedLineNumber = -1; Chris@14: public static $parsedFilename; Chris@0: Chris@0: private static $exceptionOnInvalidType = false; Chris@0: private static $objectSupport = false; Chris@0: private static $objectForMap = false; Chris@0: private static $constantSupport = false; Chris@0: Chris@0: /** Chris@14: * @param int $flags Chris@14: * @param int|null $parsedLineNumber Chris@14: * @param string|null $parsedFilename Chris@14: */ Chris@14: public static function initialize($flags, $parsedLineNumber = null, $parsedFilename = null) Chris@14: { Chris@14: self::$exceptionOnInvalidType = (bool) (Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE & $flags); Chris@14: self::$objectSupport = (bool) (Yaml::PARSE_OBJECT & $flags); Chris@14: self::$objectForMap = (bool) (Yaml::PARSE_OBJECT_FOR_MAP & $flags); Chris@14: self::$constantSupport = (bool) (Yaml::PARSE_CONSTANT & $flags); Chris@14: self::$parsedFilename = $parsedFilename; Chris@14: Chris@14: if (null !== $parsedLineNumber) { Chris@14: self::$parsedLineNumber = $parsedLineNumber; Chris@14: } Chris@14: } Chris@14: Chris@14: /** Chris@0: * Converts 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: * @param array $references Mapping of variable names to values Chris@0: * Chris@0: * @return mixed A PHP value Chris@0: * Chris@0: * @throws ParseException Chris@0: */ Chris@17: public static function parse($value, $flags = 0, $references = []) Chris@0: { Chris@17: if (\is_bool($flags)) { Chris@14: @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: 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@17: if (\func_num_args() >= 3 && !\is_array($references)) { Chris@14: @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: Chris@0: if ($references) { Chris@0: $flags |= Yaml::PARSE_OBJECT; Chris@0: } Chris@0: Chris@17: if (\func_num_args() >= 4) { Chris@14: @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: Chris@0: if (func_get_arg(3)) { Chris@0: $flags |= Yaml::PARSE_OBJECT_FOR_MAP; Chris@0: } Chris@0: } Chris@0: Chris@17: if (\func_num_args() >= 5) { Chris@0: $references = func_get_arg(4); Chris@0: } else { Chris@17: $references = []; Chris@0: } Chris@0: } Chris@0: Chris@14: self::initialize($flags); Chris@0: Chris@0: $value = trim($value); Chris@0: Chris@0: if ('' === $value) { Chris@0: return ''; Chris@0: } 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('ASCII'); Chris@0: } Chris@0: Chris@17: try { Chris@17: $i = 0; Chris@17: $tag = self::parseTag($value, $i, $flags); Chris@17: switch ($value[$i]) { Chris@17: case '[': Chris@17: $result = self::parseSequence($value, $flags, $i, $references); Chris@17: ++$i; Chris@17: break; Chris@17: case '{': Chris@17: $result = self::parseMapping($value, $flags, $i, $references); Chris@17: ++$i; Chris@17: break; Chris@17: default: Chris@17: $result = self::parseScalar($value, $flags, null, $i, null === $tag, $references); Chris@17: } Chris@17: Chris@17: if (null !== $tag) { Chris@17: return new TaggedValue($tag, $result); Chris@17: } Chris@17: Chris@17: // some comments are allowed at the end Chris@17: if (preg_replace('/\s+#.*$/A', '', substr($value, $i))) { Chris@17: throw new ParseException(sprintf('Unexpected characters near "%s".', substr($value, $i)), self::$parsedLineNumber + 1, $value, self::$parsedFilename); Chris@17: } Chris@17: Chris@17: return $result; Chris@17: } finally { Chris@17: if (isset($mbEncoding)) { Chris@17: mb_internal_encoding($mbEncoding); Chris@17: } Chris@14: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Dumps a given PHP variable to a YAML string. Chris@0: * Chris@0: * @param mixed $value The PHP variable to convert Chris@0: * @param int $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string Chris@0: * Chris@0: * @return string The YAML string representing the PHP value Chris@0: * Chris@0: * @throws DumpException When trying to dump PHP resource Chris@0: */ Chris@0: public static function dump($value, $flags = 0) Chris@0: { Chris@17: if (\is_bool($flags)) { Chris@14: @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: Chris@0: if ($flags) { Chris@0: $flags = Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE; Chris@0: } else { Chris@0: $flags = 0; Chris@0: } Chris@0: } Chris@0: Chris@17: if (\func_num_args() >= 3) { Chris@14: @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: Chris@0: if (func_get_arg(2)) { Chris@0: $flags |= Yaml::DUMP_OBJECT; Chris@0: } Chris@0: } Chris@0: Chris@0: switch (true) { Chris@17: case \is_resource($value): Chris@0: if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) { Chris@0: throw new DumpException(sprintf('Unable to dump PHP resources in a YAML file ("%s").', get_resource_type($value))); Chris@0: } Chris@0: Chris@0: return 'null'; Chris@0: case $value instanceof \DateTimeInterface: Chris@0: return $value->format('c'); Chris@17: case \is_object($value): Chris@14: if ($value instanceof TaggedValue) { Chris@14: return '!'.$value->getTag().' '.self::dump($value->getValue(), $flags); Chris@14: } Chris@14: Chris@0: if (Yaml::DUMP_OBJECT & $flags) { Chris@14: return '!php/object '.self::dump(serialize($value)); Chris@0: } Chris@0: Chris@0: if (Yaml::DUMP_OBJECT_AS_MAP & $flags && ($value instanceof \stdClass || $value instanceof \ArrayObject)) { Chris@14: return self::dumpArray($value, $flags & ~Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE); Chris@0: } Chris@0: Chris@0: if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) { Chris@0: throw new DumpException('Object support when dumping a YAML file has been disabled.'); Chris@0: } Chris@0: Chris@0: return 'null'; Chris@17: case \is_array($value): Chris@0: return self::dumpArray($value, $flags); Chris@0: case null === $value: Chris@0: return 'null'; Chris@0: case true === $value: Chris@0: return 'true'; Chris@0: case false === $value: Chris@0: return 'false'; Chris@0: case ctype_digit($value): Chris@17: return \is_string($value) ? "'$value'" : (int) $value; Chris@0: case is_numeric($value): Chris@0: $locale = setlocale(LC_NUMERIC, 0); Chris@0: if (false !== $locale) { Chris@0: setlocale(LC_NUMERIC, 'C'); Chris@0: } Chris@17: if (\is_float($value)) { Chris@0: $repr = (string) $value; Chris@0: if (is_infinite($value)) { Chris@0: $repr = str_ireplace('INF', '.Inf', $repr); Chris@0: } elseif (floor($value) == $value && $repr == $value) { Chris@0: // Preserve float data type since storing a whole number will result in integer value. Chris@0: $repr = '!!float '.$repr; Chris@0: } Chris@0: } else { Chris@17: $repr = \is_string($value) ? "'$value'" : (string) $value; Chris@0: } Chris@0: if (false !== $locale) { Chris@0: setlocale(LC_NUMERIC, $locale); Chris@0: } Chris@0: Chris@0: return $repr; Chris@0: case '' == $value: Chris@0: return "''"; Chris@0: case self::isBinaryString($value): Chris@0: return '!!binary '.base64_encode($value); Chris@0: case Escaper::requiresDoubleQuoting($value): Chris@0: return Escaper::escapeWithDoubleQuotes($value); Chris@0: case Escaper::requiresSingleQuoting($value): Chris@0: case Parser::preg_match('{^[0-9]+[_0-9]*$}', $value): Chris@0: case Parser::preg_match(self::getHexRegex(), $value): Chris@0: case Parser::preg_match(self::getTimestampRegex(), $value): Chris@0: return Escaper::escapeWithSingleQuotes($value); Chris@0: default: Chris@0: return $value; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Check if given array is hash or just normal indexed array. Chris@0: * Chris@0: * @internal Chris@0: * Chris@12: * @param array|\ArrayObject|\stdClass $value The PHP array or array-like object to check Chris@0: * Chris@0: * @return bool true if value is hash array, false otherwise Chris@0: */ Chris@12: public static function isHash($value) Chris@0: { Chris@12: if ($value instanceof \stdClass || $value instanceof \ArrayObject) { Chris@12: return true; Chris@12: } Chris@12: Chris@0: $expectedKey = 0; Chris@0: Chris@0: foreach ($value as $key => $val) { Chris@0: if ($key !== $expectedKey++) { Chris@0: return true; Chris@0: } Chris@0: } Chris@0: Chris@0: return false; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Dumps a PHP array to a YAML string. Chris@0: * Chris@0: * @param array $value The PHP array to dump Chris@0: * @param int $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string Chris@0: * Chris@0: * @return string The YAML string representing the PHP array Chris@0: */ Chris@0: private static function dumpArray($value, $flags) Chris@0: { Chris@0: // array Chris@14: if (($value || Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE & $flags) && !self::isHash($value)) { Chris@17: $output = []; Chris@0: foreach ($value as $val) { Chris@0: $output[] = self::dump($val, $flags); Chris@0: } Chris@0: Chris@0: return sprintf('[%s]', implode(', ', $output)); Chris@0: } Chris@0: Chris@0: // hash Chris@17: $output = []; Chris@0: foreach ($value as $key => $val) { Chris@0: $output[] = sprintf('%s: %s', self::dump($key, $flags), self::dump($val, $flags)); Chris@0: } Chris@0: Chris@0: return sprintf('{ %s }', implode(', ', $output)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Parses a YAML scalar. Chris@0: * Chris@0: * @param string $scalar Chris@0: * @param int $flags Chris@0: * @param string[] $delimiters Chris@0: * @param int &$i Chris@0: * @param bool $evaluate Chris@0: * @param array $references Chris@0: * Chris@0: * @return string Chris@0: * Chris@0: * @throws ParseException When malformed inline YAML string is parsed Chris@0: * Chris@0: * @internal Chris@0: */ Chris@17: public static function parseScalar($scalar, $flags = 0, $delimiters = null, &$i = 0, $evaluate = true, $references = [], $legacyOmittedKeySupport = false) Chris@0: { Chris@17: if (\in_array($scalar[$i], ['"', "'"])) { Chris@0: // quoted scalar Chris@0: $output = self::parseQuotedScalar($scalar, $i); Chris@0: Chris@0: if (null !== $delimiters) { Chris@0: $tmp = ltrim(substr($scalar, $i), ' '); Chris@16: if ('' === $tmp) { Chris@17: throw new ParseException(sprintf('Unexpected end of line, expected one of "%s".', implode('', $delimiters)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); Chris@16: } Chris@17: if (!\in_array($tmp[0], $delimiters)) { Chris@14: throw new ParseException(sprintf('Unexpected characters (%s).', substr($scalar, $i)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); Chris@0: } Chris@0: } Chris@0: } else { Chris@0: // "normal" string Chris@0: if (!$delimiters) { Chris@0: $output = substr($scalar, $i); Chris@17: $i += \strlen($output); Chris@0: Chris@0: // remove comments Chris@0: if (Parser::preg_match('/[ \t]+#/', $output, $match, PREG_OFFSET_CAPTURE)) { Chris@0: $output = substr($output, 0, $match[0][1]); Chris@0: } Chris@14: } elseif (Parser::preg_match('/^(.'.($legacyOmittedKeySupport ? '+' : '*').'?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) { Chris@0: $output = $match[1]; Chris@17: $i += \strlen($output); Chris@0: } else { Chris@14: throw new ParseException(sprintf('Malformed inline YAML string: %s.', $scalar), self::$parsedLineNumber + 1, null, self::$parsedFilename); Chris@0: } Chris@0: Chris@0: // a non-quoted string cannot start with @ or ` (reserved) nor with a scalar indicator (| or >) Chris@0: if ($output && ('@' === $output[0] || '`' === $output[0] || '|' === $output[0] || '>' === $output[0])) { Chris@14: 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: } Chris@0: Chris@0: if ($output && '%' === $output[0]) { Chris@14: @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: } Chris@0: Chris@0: if ($evaluate) { Chris@0: $output = self::evaluateScalar($output, $flags, $references); Chris@0: } Chris@0: } Chris@0: Chris@0: return $output; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Parses a YAML quoted scalar. Chris@0: * Chris@0: * @param string $scalar Chris@0: * @param int &$i Chris@0: * Chris@0: * @return string Chris@0: * Chris@0: * @throws ParseException When malformed inline YAML string is parsed Chris@0: */ Chris@0: private static function parseQuotedScalar($scalar, &$i) Chris@0: { Chris@0: if (!Parser::preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) { Chris@14: throw new ParseException(sprintf('Malformed inline YAML string: %s.', substr($scalar, $i)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); Chris@0: } Chris@0: Chris@17: $output = substr($match[0], 1, \strlen($match[0]) - 2); Chris@0: Chris@0: $unescaper = new Unescaper(); Chris@0: if ('"' == $scalar[$i]) { Chris@0: $output = $unescaper->unescapeDoubleQuotedString($output); Chris@0: } else { Chris@0: $output = $unescaper->unescapeSingleQuotedString($output); Chris@0: } Chris@0: Chris@17: $i += \strlen($match[0]); Chris@0: Chris@0: return $output; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Parses a YAML sequence. Chris@0: * Chris@0: * @param string $sequence Chris@0: * @param int $flags Chris@0: * @param int &$i Chris@0: * @param array $references Chris@0: * Chris@0: * @return array Chris@0: * Chris@0: * @throws ParseException When malformed inline YAML string is parsed Chris@0: */ Chris@17: private static function parseSequence($sequence, $flags, &$i = 0, $references = []) Chris@0: { Chris@17: $output = []; Chris@17: $len = \strlen($sequence); Chris@0: ++$i; Chris@0: Chris@0: // [foo, bar, ...] Chris@0: while ($i < $len) { Chris@14: if (']' === $sequence[$i]) { Chris@14: return $output; Chris@14: } Chris@14: if (',' === $sequence[$i] || ' ' === $sequence[$i]) { Chris@14: ++$i; Chris@14: Chris@14: continue; Chris@14: } Chris@14: Chris@14: $tag = self::parseTag($sequence, $i, $flags); Chris@0: switch ($sequence[$i]) { Chris@0: case '[': Chris@0: // nested sequence Chris@14: $value = self::parseSequence($sequence, $flags, $i, $references); Chris@0: break; Chris@0: case '{': Chris@0: // nested mapping Chris@14: $value = self::parseMapping($sequence, $flags, $i, $references); Chris@0: break; Chris@0: default: Chris@17: $isQuoted = \in_array($sequence[$i], ['"', "'"]); Chris@17: $value = self::parseScalar($sequence, $flags, [',', ']'], $i, null === $tag, $references); Chris@0: Chris@0: // the value can be an array if a reference has been resolved to an array var Chris@17: if (\is_string($value) && !$isQuoted && false !== strpos($value, ': ')) { Chris@0: // embedded mapping? Chris@0: try { Chris@0: $pos = 0; Chris@0: $value = self::parseMapping('{'.$value.'}', $flags, $pos, $references); Chris@0: } catch (\InvalidArgumentException $e) { Chris@0: // no, it's not Chris@0: } Chris@0: } Chris@0: Chris@0: --$i; Chris@0: } Chris@0: Chris@14: if (null !== $tag) { Chris@14: $value = new TaggedValue($tag, $value); Chris@14: } Chris@14: Chris@14: $output[] = $value; Chris@14: Chris@0: ++$i; Chris@0: } Chris@0: Chris@14: throw new ParseException(sprintf('Malformed inline YAML string: %s.', $sequence), self::$parsedLineNumber + 1, null, self::$parsedFilename); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Parses a YAML mapping. Chris@0: * Chris@0: * @param string $mapping Chris@0: * @param int $flags Chris@0: * @param int &$i Chris@0: * @param array $references Chris@0: * Chris@0: * @return array|\stdClass Chris@0: * Chris@0: * @throws ParseException When malformed inline YAML string is parsed Chris@0: */ Chris@17: private static function parseMapping($mapping, $flags, &$i = 0, $references = []) Chris@0: { Chris@17: $output = []; Chris@17: $len = \strlen($mapping); Chris@0: ++$i; Chris@14: $allowOverwrite = false; Chris@0: Chris@0: // {foo: bar, bar:foo, ...} Chris@0: while ($i < $len) { Chris@0: switch ($mapping[$i]) { Chris@0: case ' ': Chris@0: case ',': Chris@0: ++$i; Chris@0: continue 2; Chris@0: case '}': Chris@0: if (self::$objectForMap) { Chris@0: return (object) $output; Chris@0: } Chris@0: Chris@0: return $output; Chris@0: } Chris@0: Chris@0: // key Chris@17: $isKeyQuoted = \in_array($mapping[$i], ['"', "'"], true); Chris@17: $key = self::parseScalar($mapping, $flags, [':', ' '], $i, false, [], true); Chris@0: Chris@0: if (':' !== $key && false === $i = strpos($mapping, ':', $i)) { Chris@0: break; Chris@0: } Chris@0: Chris@14: if (':' === $key) { Chris@14: @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: } Chris@0: Chris@14: if (!$isKeyQuoted) { Chris@14: $evaluatedKey = self::evaluateScalar($key, $flags, $references); Chris@14: Chris@17: if ('' !== $key && $evaluatedKey !== $key && !\is_string($evaluatedKey) && !\is_int($evaluatedKey)) { Chris@14: @trigger_error(self::getDeprecationMessage('Implicit casting of incompatible mapping keys to strings is deprecated since Symfony 3.3 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0. Quote your evaluable mapping keys instead.'), E_USER_DEPRECATED); Chris@14: } Chris@14: } Chris@14: Chris@17: if (':' !== $key && !$isKeyQuoted && (!isset($mapping[$i + 1]) || !\in_array($mapping[$i + 1], [' ', ',', '[', ']', '{', '}'], true))) { Chris@14: @trigger_error(self::getDeprecationMessage('Using a colon after an unquoted mapping key that is not followed by an indication character (i.e. " ", ",", "[", "]", "{", "}") is deprecated since Symfony 3.2 and will throw a ParseException in 4.0.'), E_USER_DEPRECATED); Chris@14: } Chris@14: Chris@14: if ('<<' === $key) { Chris@14: $allowOverwrite = true; Chris@14: } Chris@0: Chris@0: while ($i < $len) { Chris@14: if (':' === $mapping[$i] || ' ' === $mapping[$i]) { Chris@14: ++$i; Chris@14: Chris@14: continue; Chris@14: } Chris@14: Chris@14: $tag = self::parseTag($mapping, $i, $flags); Chris@0: switch ($mapping[$i]) { Chris@0: case '[': Chris@0: // nested sequence Chris@0: $value = self::parseSequence($mapping, $flags, $i, $references); Chris@0: // Spec: Keys MUST be unique; first one wins. Chris@0: // Parser cannot abort this mapping earlier, since lines Chris@0: // are processed sequentially. Chris@14: // But overwriting is allowed when a merge node is used in current block. Chris@14: if ('<<' === $key) { Chris@14: foreach ($value as $parsedValue) { Chris@14: $output += $parsedValue; Chris@14: } Chris@14: } elseif ($allowOverwrite || !isset($output[$key])) { Chris@14: if (null !== $tag) { Chris@14: $output[$key] = new TaggedValue($tag, $value); Chris@14: } else { Chris@14: $output[$key] = $value; Chris@14: } Chris@14: } elseif (isset($output[$key])) { Chris@14: @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: } Chris@0: break; Chris@0: case '{': Chris@0: // nested mapping Chris@0: $value = self::parseMapping($mapping, $flags, $i, $references); Chris@0: // Spec: Keys MUST be unique; first one wins. Chris@0: // Parser cannot abort this mapping earlier, since lines Chris@0: // are processed sequentially. Chris@14: // But overwriting is allowed when a merge node is used in current block. Chris@14: if ('<<' === $key) { Chris@14: $output += $value; Chris@14: } elseif ($allowOverwrite || !isset($output[$key])) { Chris@14: if (null !== $tag) { Chris@14: $output[$key] = new TaggedValue($tag, $value); Chris@14: } else { Chris@14: $output[$key] = $value; Chris@14: } Chris@14: } elseif (isset($output[$key])) { Chris@14: @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: } Chris@0: break; Chris@0: default: Chris@17: $value = self::parseScalar($mapping, $flags, [',', '}'], $i, null === $tag, $references); Chris@0: // Spec: Keys MUST be unique; first one wins. Chris@0: // Parser cannot abort this mapping earlier, since lines Chris@0: // are processed sequentially. Chris@14: // But overwriting is allowed when a merge node is used in current block. Chris@14: if ('<<' === $key) { Chris@14: $output += $value; Chris@14: } elseif ($allowOverwrite || !isset($output[$key])) { Chris@14: if (null !== $tag) { Chris@14: $output[$key] = new TaggedValue($tag, $value); Chris@14: } else { Chris@14: $output[$key] = $value; Chris@14: } Chris@14: } elseif (isset($output[$key])) { Chris@14: @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: } Chris@0: --$i; Chris@0: } Chris@0: ++$i; Chris@0: Chris@14: continue 2; Chris@0: } Chris@0: } Chris@0: Chris@14: throw new ParseException(sprintf('Malformed inline YAML string: %s.', $mapping), self::$parsedLineNumber + 1, null, self::$parsedFilename); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Evaluates scalars and replaces magic values. Chris@0: * Chris@0: * @param string $scalar Chris@0: * @param int $flags Chris@0: * @param array $references Chris@0: * Chris@0: * @return mixed The evaluated YAML string Chris@0: * Chris@0: * @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: */ Chris@17: private static function evaluateScalar($scalar, $flags, $references = []) Chris@0: { Chris@0: $scalar = trim($scalar); Chris@0: $scalarLower = strtolower($scalar); Chris@0: Chris@0: if (0 === strpos($scalar, '*')) { Chris@0: if (false !== $pos = strpos($scalar, '#')) { Chris@0: $value = substr($scalar, 1, $pos - 2); Chris@0: } else { Chris@0: $value = substr($scalar, 1); Chris@0: } Chris@0: Chris@0: // an unquoted * Chris@0: if (false === $value || '' === $value) { Chris@14: throw new ParseException('A reference must contain at least one character.', self::$parsedLineNumber + 1, $value, self::$parsedFilename); Chris@0: } Chris@0: Chris@18: if (!\array_key_exists($value, $references)) { Chris@14: throw new ParseException(sprintf('Reference "%s" does not exist.', $value), self::$parsedLineNumber + 1, $value, self::$parsedFilename); Chris@0: } Chris@0: Chris@0: return $references[$value]; Chris@0: } Chris@0: Chris@0: switch (true) { Chris@0: case 'null' === $scalarLower: Chris@0: case '' === $scalar: Chris@0: case '~' === $scalar: Chris@0: return; Chris@0: case 'true' === $scalarLower: Chris@0: return true; Chris@0: case 'false' === $scalarLower: Chris@0: return false; Chris@14: case '!' === $scalar[0]: Chris@0: switch (true) { Chris@0: case 0 === strpos($scalar, '!str'): Chris@14: @trigger_error(self::getDeprecationMessage('Support for the !str tag is deprecated since Symfony 3.4. Use the !!str tag instead.'), E_USER_DEPRECATED); Chris@14: Chris@0: return (string) substr($scalar, 5); Chris@14: case 0 === strpos($scalar, '!!str '): Chris@14: return (string) substr($scalar, 6); Chris@0: case 0 === strpos($scalar, '! '): Chris@14: @trigger_error(self::getDeprecationMessage('Using the non-specific tag "!" is deprecated since Symfony 3.4 as its behavior will change in 4.0. It will force non-evaluating your values in 4.0. Use plain integers or !!float instead.'), E_USER_DEPRECATED); Chris@14: Chris@0: return (int) self::parseScalar(substr($scalar, 2), $flags); Chris@0: case 0 === strpos($scalar, '!php/object:'): Chris@0: if (self::$objectSupport) { Chris@14: @trigger_error(self::getDeprecationMessage('The !php/object: tag to indicate dumped PHP objects is deprecated since Symfony 3.4 and will be removed in 4.0. Use the !php/object (without the colon) tag instead.'), E_USER_DEPRECATED); Chris@14: Chris@0: return unserialize(substr($scalar, 12)); Chris@0: } Chris@0: Chris@0: if (self::$exceptionOnInvalidType) { Chris@14: throw new ParseException('Object support when parsing a YAML file has been disabled.', self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); Chris@0: } Chris@0: Chris@0: return; Chris@0: case 0 === strpos($scalar, '!!php/object:'): Chris@0: if (self::$objectSupport) { Chris@14: @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: Chris@0: return unserialize(substr($scalar, 13)); Chris@0: } Chris@0: Chris@0: if (self::$exceptionOnInvalidType) { Chris@14: throw new ParseException('Object support when parsing a YAML file has been disabled.', self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); Chris@14: } Chris@14: Chris@14: return; Chris@14: case 0 === strpos($scalar, '!php/object'): Chris@14: if (self::$objectSupport) { Chris@14: return unserialize(self::parseScalar(substr($scalar, 12))); Chris@14: } Chris@14: Chris@14: if (self::$exceptionOnInvalidType) { Chris@14: throw new ParseException('Object support when parsing a YAML file has been disabled.', self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); Chris@0: } Chris@0: Chris@0: return; Chris@0: case 0 === strpos($scalar, '!php/const:'): Chris@0: if (self::$constantSupport) { Chris@14: @trigger_error(self::getDeprecationMessage('The !php/const: tag to indicate dumped PHP constants is deprecated since Symfony 3.4 and will be removed in 4.0. Use the !php/const (without the colon) tag instead.'), E_USER_DEPRECATED); Chris@14: Chris@17: if (\defined($const = substr($scalar, 11))) { Chris@17: return \constant($const); Chris@0: } Chris@0: Chris@14: throw new ParseException(sprintf('The constant "%s" is not defined.', $const), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); Chris@0: } Chris@0: if (self::$exceptionOnInvalidType) { Chris@14: throw new ParseException(sprintf('The string "%s" could not be parsed as a constant. Have you forgotten to pass the "Yaml::PARSE_CONSTANT" flag to the parser?', $scalar), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); Chris@14: } Chris@14: Chris@14: return; Chris@14: case 0 === strpos($scalar, '!php/const'): Chris@14: if (self::$constantSupport) { Chris@14: $i = 0; Chris@17: if (\defined($const = self::parseScalar(substr($scalar, 11), 0, null, $i, false))) { Chris@17: return \constant($const); Chris@14: } Chris@14: Chris@14: throw new ParseException(sprintf('The constant "%s" is not defined.', $const), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); Chris@14: } Chris@14: if (self::$exceptionOnInvalidType) { Chris@14: 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: } Chris@0: Chris@0: return; Chris@0: case 0 === strpos($scalar, '!!float '): Chris@0: return (float) substr($scalar, 8); Chris@14: case 0 === strpos($scalar, '!!binary '): Chris@14: return self::evaluateBinaryScalar(substr($scalar, 9)); Chris@14: default: Chris@14: @trigger_error(self::getDeprecationMessage(sprintf('Using the unquoted scalar value "%s" is deprecated since Symfony 3.3 and will be considered as a tagged value in 4.0. You must quote it.', $scalar)), E_USER_DEPRECATED); Chris@14: } Chris@14: Chris@14: // Optimize for returning strings. Chris@14: // no break Chris@14: case '+' === $scalar[0] || '-' === $scalar[0] || '.' === $scalar[0] || is_numeric($scalar[0]): Chris@14: switch (true) { Chris@0: case Parser::preg_match('{^[+-]?[0-9][0-9_]*$}', $scalar): Chris@0: $scalar = str_replace('_', '', (string) $scalar); Chris@0: // omitting the break / return as integers are handled in the next case Chris@14: // no break Chris@0: case ctype_digit($scalar): Chris@0: $raw = $scalar; Chris@0: $cast = (int) $scalar; Chris@0: Chris@0: return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw); Chris@0: case '-' === $scalar[0] && ctype_digit(substr($scalar, 1)): Chris@0: $raw = $scalar; Chris@0: $cast = (int) $scalar; Chris@0: Chris@0: return '0' == $scalar[1] ? octdec($scalar) : (((string) $raw === (string) $cast) ? $cast : $raw); Chris@0: case is_numeric($scalar): Chris@0: case Parser::preg_match(self::getHexRegex(), $scalar): Chris@0: $scalar = str_replace('_', '', $scalar); Chris@0: Chris@0: return '0x' === $scalar[0].$scalar[1] ? hexdec($scalar) : (float) $scalar; Chris@0: case '.inf' === $scalarLower: Chris@0: case '.nan' === $scalarLower: Chris@0: return -log(0); Chris@0: case '-.inf' === $scalarLower: Chris@0: return log(0); Chris@0: case Parser::preg_match('/^(-|\+)?[0-9][0-9,]*(\.[0-9_]+)?$/', $scalar): Chris@0: case Parser::preg_match('/^(-|\+)?[0-9][0-9_]*(\.[0-9_]+)?$/', $scalar): Chris@0: if (false !== strpos($scalar, ',')) { Chris@14: @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: } Chris@0: Chris@17: return (float) str_replace([',', '_'], '', $scalar); Chris@0: case Parser::preg_match(self::getTimestampRegex(), $scalar): Chris@0: if (Yaml::PARSE_DATETIME & $flags) { Chris@0: // When no timezone is provided in the parsed date, YAML spec says we must assume UTC. Chris@0: return new \DateTime($scalar, new \DateTimeZone('UTC')); Chris@0: } Chris@0: Chris@0: $timeZone = date_default_timezone_get(); Chris@0: date_default_timezone_set('UTC'); Chris@0: $time = strtotime($scalar); Chris@0: date_default_timezone_set($timeZone); Chris@0: Chris@0: return $time; Chris@0: } Chris@0: } Chris@14: Chris@14: return (string) $scalar; Chris@14: } Chris@14: Chris@14: /** Chris@14: * @param string $value Chris@14: * @param int &$i Chris@14: * @param int $flags Chris@14: * Chris@17: * @return string|null Chris@14: */ Chris@14: private static function parseTag($value, &$i, $flags) Chris@14: { Chris@14: if ('!' !== $value[$i]) { Chris@14: return; Chris@14: } Chris@14: Chris@14: $tagLength = strcspn($value, " \t\n", $i + 1); Chris@14: $tag = substr($value, $i + 1, $tagLength); Chris@14: Chris@14: $nextOffset = $i + $tagLength + 1; Chris@14: $nextOffset += strspn($value, ' ', $nextOffset); Chris@14: Chris@14: // Is followed by a scalar Chris@17: if ((!isset($value[$nextOffset]) || !\in_array($value[$nextOffset], ['[', '{'], true)) && 'tagged' !== $tag) { Chris@14: // Manage non-whitelisted scalars in {@link self::evaluateScalar()} Chris@14: return; Chris@14: } Chris@14: Chris@14: // Built-in tags Chris@14: if ($tag && '!' === $tag[0]) { Chris@14: throw new ParseException(sprintf('The built-in tag "!%s" is not implemented.', $tag), self::$parsedLineNumber + 1, $value, self::$parsedFilename); Chris@14: } Chris@14: Chris@14: if (Yaml::PARSE_CUSTOM_TAGS & $flags) { Chris@14: $i = $nextOffset; Chris@14: Chris@14: return $tag; Chris@14: } Chris@14: Chris@14: 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: } Chris@0: Chris@0: /** Chris@0: * @param string $scalar Chris@0: * Chris@0: * @return string Chris@0: * Chris@0: * @internal Chris@0: */ Chris@0: public static function evaluateBinaryScalar($scalar) Chris@0: { Chris@0: $parsedBinaryData = self::parseScalar(preg_replace('/\s/', '', $scalar)); Chris@0: Chris@17: if (0 !== (\strlen($parsedBinaryData) % 4)) { Chris@17: 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: } Chris@0: Chris@0: if (!Parser::preg_match('#^[A-Z0-9+/]+={0,2}$#i', $parsedBinaryData)) { Chris@14: throw new ParseException(sprintf('The base64 encoded data (%s) contains invalid characters.', $parsedBinaryData), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); Chris@0: } Chris@0: Chris@0: return base64_decode($parsedBinaryData, true); Chris@0: } Chris@0: Chris@0: private static function isBinaryString($value) Chris@0: { Chris@0: return !preg_match('//u', $value) || preg_match('/[^\x00\x07-\x0d\x1B\x20-\xff]/', $value); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets a regex that matches a YAML date. Chris@0: * Chris@0: * @return string The regular expression Chris@0: * Chris@0: * @see http://www.yaml.org/spec/1.2/spec.html#id2761573 Chris@0: */ Chris@0: private static function getTimestampRegex() Chris@0: { Chris@0: return <<[0-9][0-9][0-9][0-9]) Chris@0: -(?P[0-9][0-9]?) Chris@0: -(?P[0-9][0-9]?) Chris@0: (?:(?:[Tt]|[ \t]+) Chris@0: (?P[0-9][0-9]?) Chris@0: :(?P[0-9][0-9]) Chris@0: :(?P[0-9][0-9]) Chris@0: (?:\.(?P[0-9]*))? Chris@0: (?:[ \t]*(?PZ|(?P[-+])(?P[0-9][0-9]?) Chris@0: (?::(?P[0-9][0-9]))?))?)? Chris@0: $~x Chris@0: EOF; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets a regex that matches a YAML number in hexadecimal notation. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private static function getHexRegex() Chris@0: { Chris@0: return '~^0x[0-9a-f_]++$~i'; Chris@0: } Chris@14: Chris@14: private static function getDeprecationMessage($message) Chris@14: { Chris@14: $message = rtrim($message, '.'); Chris@14: Chris@14: if (null !== self::$parsedFilename) { Chris@14: $message .= ' in '.self::$parsedFilename; Chris@14: } Chris@14: Chris@14: if (-1 !== self::$parsedLineNumber) { Chris@14: $message .= ' on line '.(self::$parsedLineNumber + 1); Chris@14: } Chris@14: Chris@14: return $message.'.'; Chris@14: } Chris@0: }