Exemple #1
0
 public function validateValueAsYaml(ExecutionContext $context)
 {
     try {
         Inline::load($this->value);
     } catch (ParserException $e) {
         $context->setPropertyPath($context->getPropertyPath() . '.value');
         $context->addViolation('This value is not valid YAML syntax', array(), $this->value);
     }
 }
 /**
  * Dumps a PHP value to YAML.
  *
  * @param mixed $input                  The PHP value
  * @param int   $inline                 The level where you switch to inline YAML
  * @param int   $indent                 The level of indentation (used internally)
  * @param bool  $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
  * @param bool  $objectSupport          true if object support is enabled, false otherwise
  *
  * @return string The YAML representation of the PHP value
  */
 public function dump($input, $inline = 0, $indent = 0, $exceptionOnInvalidType = false, $objectSupport = false)
 {
     $output = '';
     $prefix = $indent ? str_repeat(' ', $indent) : '';
     if ($inline <= 0 || !is_array($input) || empty($input)) {
         $output .= $prefix . Inline::dump($input, $exceptionOnInvalidType, $objectSupport);
     } else {
         $isAHash = array_keys($input) !== range(0, count($input) - 1);
         foreach ($input as $key => $value) {
             $willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value);
             $output .= sprintf('%s%s%s%s', $prefix, $isAHash ? Inline::dump($key, $exceptionOnInvalidType, $objectSupport) . ':' : '-', $willBeInlined ? ' ' : "\n", $this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + $this->indentation, $exceptionOnInvalidType, $objectSupport)) . ($willBeInlined ? "\n" : '');
         }
     }
     return str_replace("'''", "'", $output);
 }
 /**
  * @param string $name
  *
  * @return array|string|bool|int|float|null
  */
 public function getParameter($name)
 {
     if (!isset($this->parameterMap[$name])) {
         return $this->container->getParameter($name);
     }
     $varName = $this->parameterMap[$name]['variable'];
     $var = getenv($varName);
     if (false === $var) {
         return $this->container->getParameter($name);
     }
     if ($this->parameterMap[$name]['yaml']) {
         return Inline::parse($var);
     }
     return $var;
 }
Exemple #4
0
 public function testDump()
 {
     $testsForDump = $this->getTestsForDump();
     foreach ($testsForDump as $yaml => $value) {
         $this->assertEquals($yaml, Inline::dump($value), sprintf('::dump() converts a PHP structure to an inline YAML (%s)', $yaml));
     }
     foreach ($this->getTestsForLoad() as $yaml => $value) {
         if ($value == 1230) {
             continue;
         }
         $this->assertEquals($value, Inline::load(Inline::dump($value)), 'check consistency');
     }
     foreach ($testsForDump as $yaml => $value) {
         if ($value == 1230) {
             continue;
         }
         $this->assertEquals($value, Inline::load(Inline::dump($value)), 'check consistency');
     }
 }
 public function getFunctions()
 {
     return array(new ExpressionFunction('dynamic_parameter', function ($paramName, $envVar) {
         return sprintf('(false === getenv(%s) ? $this->getParameter(%s) : getenv(%s))', $envVar, $paramName, $envVar);
     }, function (array $variables, $paramName, $envVar) {
         $envParam = getenv($envVar);
         if (false !== $envParam) {
             return $envParam;
         }
         return $variables['container']->getParameter($paramName);
     }), new ExpressionFunction('dynamic_yaml_parameter', function ($paramName, $envVar) {
         return sprintf('(false === getenv(%s) ? $this->getParameter(%s) : \\Symfony\\Component\\Yaml\\Inline::parse(getenv(%s)))', $envVar, $paramName, $envVar);
     }, function (array $variables, $paramName, $envVar) {
         $envParam = getenv($envVar);
         if (false !== $envParam) {
             return Inline::parse($envParam);
         }
         return $variables['container']->getParameter($paramName);
     }));
 }
Exemple #6
0
 /**
  * Dumps a PHP value to YAML.
  *
  * @param  mixed   $input  The PHP value
  * @param  integer $inline The level where you switch to inline YAML
  * @param  integer $indent The level of indentation (used internally)
  *
  * @return string  The YAML representation of the PHP value
  */
 public function dump($input, $inline = 0, $indent = 0)
 {
     $output = '';
     $prefix = $indent ? str_repeat(' ', $indent) : '';
     if ($inline <= 0 || !is_array($input) || empty($input)) {
         $output .= $prefix . Inline::dump($input);
     } else {
         $isAHash = array_keys($input) !== range(0, count($input) - 1);
         if ($isAHash) {
             foreach ($input as $key => $value) {
                 $willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value);
                 $output .= sprintf('%s%s%s%s', $prefix, $isAHash ? Inline::dump($key) . ':' : '-', $willBeInlined ? ' ' : "\n", $this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + 4)) . ($willBeInlined ? "\n" : '');
             }
         } else {
             foreach ($input as $key => $value) {
                 $output .= sprintf('%s%s%s%s', $prefix, '- ', Inline::dump($value), "\n");
             }
         }
     }
     return $output;
 }
 private function dumpStructureRecursively(array $structure)
 {
     $isFirst = true;
     $precededByMessage = false;
     foreach ($structure as $k => $v) {
         if ($isMessage = $v instanceof Message) {
             $desc = $v->getDesc();
             $meaning = $v->getMeaning();
             if (!$isFirst && (!$precededByMessage || $desc || $meaning)) {
                 $this->writer->write("\n");
             }
             if ($desc) {
                 $desc = str_replace(array("\r\n", "\n", "\r", "\t"), array('\\r\\n', '\\n', '\\r', '\\t'), $desc);
                 $this->writer->writeln('# Desc: ' . $desc);
             }
             if ($meaning) {
                 $this->writer->writeln('# Meaning: ' . $meaning);
             }
         } else {
             if (!$isFirst) {
                 $this->writer->write("\n");
             }
         }
         $isFirst = false;
         $precededByMessage = $isMessage;
         $this->writer->write(Inline::dump($k) . ':');
         if ($isMessage) {
             $this->writer->write(' ' . Inline::dump($v->getLocaleString()));
             if ($v->isNew()) {
                 $this->writer->write('   # FIXME');
             }
             $this->writer->write("\n");
             continue;
         }
         $this->writer->write("\n")->indent();
         $this->dumpStructureRecursively($v);
         $this->writer->outdent();
     }
 }
Exemple #8
0
 public function serialize(VisitorInterface $visitor, $data, $type, &$visited)
 {
     if (!$data instanceof \DateTime) {
         return;
     }
     if ($visitor instanceof XmlSerializationVisitor) {
         if (null === $visitor->document) {
             $visitor->document = $visitor->createDocument(null, null, true);
         }
         $visited = true;
         return $visitor->document->createTextNode($data->format($this->format));
     } else {
         if ($visitor instanceof GenericSerializationVisitor) {
             $visited = true;
             return $data->format($this->format);
         } else {
             if ($visitor instanceof YamlSerializationVisitor) {
                 $visited = true;
                 return Inline::dump($data->format($this->format));
             }
         }
     }
 }
 public function visitProperty(PropertyMetadata $metadata, $data, Context $context)
 {
     $v = $metadata->getValue($data);
     if (null === $v && !$context->shouldSerializeNull()) {
         return;
     }
     $name = $this->namingStrategy->translateName($metadata);
     if (!$metadata->inline) {
         $this->writer->writeln(Inline::dump($name) . ':')->indent();
     }
     $this->setCurrentMetadata($metadata);
     $count = $this->writer->changeCount;
     if (null !== ($v = $this->navigator->accept($v, $metadata->type, $context))) {
         $this->writer->rtrim(false)->writeln(' ' . $v);
     } elseif ($count === $this->writer->changeCount && !$metadata->inline) {
         $this->writer->revert();
     }
     if (!$metadata->inline) {
         $this->writer->outdent();
     }
     $this->revertCurrentMetadata();
 }
 /**
  * @param NodeInterface $node
  * @param int           $depth
  */
 private function writeNode(NodeInterface $node, $depth = 0)
 {
     $comments = array();
     $default = '';
     $defaultArray = null;
     $children = null;
     $example = $node->getExample();
     // defaults
     if ($node instanceof ArrayNode) {
         $children = $node->getChildren();
         if ($node instanceof PrototypedArrayNode) {
             $prototype = $node->getPrototype();
             if ($prototype instanceof ArrayNode) {
                 $children = $prototype->getChildren();
             }
             // check for attribute as key
             if ($key = $node->getKeyAttribute()) {
                 $keyNodeClass = 'Symfony\\Component\\Config\\Definition\\' . ($prototype instanceof ArrayNode ? 'ArrayNode' : 'ScalarNode');
                 $keyNode = new $keyNodeClass($key, $node);
                 $keyNode->setInfo('Prototype');
                 // add children
                 foreach ($children as $childNode) {
                     $keyNode->addChild($childNode);
                 }
                 $children = array($key => $keyNode);
             }
         }
         if (!$children) {
             if ($node->hasDefaultValue() && count($defaultArray = $node->getDefaultValue())) {
                 $default = '';
             } elseif (!is_array($example)) {
                 $default = '[]';
             }
         }
     } elseif ($node instanceof EnumNode) {
         $comments[] = 'One of ' . implode('; ', array_map('json_encode', $node->getValues()));
         $default = $node->hasDefaultValue() ? Inline::dump($node->getDefaultValue()) : '~';
     } else {
         $default = '~';
         if ($node->hasDefaultValue()) {
             $default = $node->getDefaultValue();
             if (is_array($default)) {
                 if (count($defaultArray = $node->getDefaultValue())) {
                     $default = '';
                 } elseif (!is_array($example)) {
                     $default = '[]';
                 }
             } else {
                 $default = Inline::dump($default);
             }
         }
     }
     // required?
     if ($node->isRequired()) {
         $comments[] = 'Required';
     }
     // example
     if ($example && !is_array($example)) {
         $comments[] = 'Example: ' . $example;
     }
     $default = (string) $default != '' ? ' ' . $default : '';
     $comments = count($comments) ? '# ' . implode(', ', $comments) : '';
     $text = rtrim(sprintf('%-20s %s %s', $node->getName() . ':', $default, $comments), ' ');
     if ($info = $node->getInfo()) {
         $this->writeLine('');
         // indenting multi-line info
         $info = str_replace("\n", sprintf("\n%" . $depth * 4 . 's# ', ' '), $info);
         $this->writeLine('# ' . $info, $depth * 4);
     }
     $this->writeLine($text, $depth * 4);
     // output defaults
     if ($defaultArray) {
         $this->writeLine('');
         $message = count($defaultArray) > 1 ? 'Defaults' : 'Weather';
         $this->writeLine('# ' . $message . ':', $depth * 4 + 4);
         $this->writeArray($defaultArray, $depth + 1);
     }
     if (is_array($example)) {
         $this->writeLine('');
         $message = count($example) > 1 ? 'Examples' : 'Example';
         $this->writeLine('# ' . $message . ':', $depth * 4 + 4);
         $this->writeArray($example, $depth + 1);
     }
     if ($children) {
         foreach ($children as $childNode) {
             $this->writeNode($childNode, $depth + 1);
         }
     }
 }
Exemple #11
0
 /**
  * @expectedException \Symfony\Component\Yaml\Exception\ParseException
  * @expectedExceptionMessage Malformed inline YAML string: {this, is not, supported}.
  */
 public function testNotSupportedMissingValue()
 {
     Inline::parse('{this, is not, supported}');
 }
 public function testParseScalarWithCorrectlyQuotedStringShouldReturnString()
 {
     $value = "'don''t do somthin'' like that'";
     $expect = "don't do somthin' like that";
     $this->assertSame($expect, Inline::parseScalar($value));
 }
 /**
  * Parses a YAML value.
  *
  * @param string $value                  A YAML value
  * @param bool   $exceptionOnInvalidType True if an exception must be thrown on invalid types false otherwise
  * @param bool   $objectSupport          True if object support is enabled, false otherwise
  * @param bool   $objectForMap           true if maps should return a stdClass instead of array()
  * @param string $context                The parser context (either sequence or mapping)
  *
  * @return mixed A PHP value
  *
  * @throws ParseException When reference does not exist
  */
 private function parseValue($value, $exceptionOnInvalidType, $objectSupport, $objectForMap, $context)
 {
     if (0 === strpos($value, '*')) {
         if (false !== ($pos = strpos($value, '#'))) {
             $value = substr($value, 1, $pos - 2);
         } else {
             $value = substr($value, 1);
         }
         if (!array_key_exists($value, $this->refs)) {
             throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLine);
         }
         return $this->refs[$value];
     }
     if (preg_match('/^' . self::BLOCK_SCALAR_HEADER_PATTERN . '$/', $value, $matches)) {
         $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
         return $this->parseBlockScalar($matches['separator'], preg_replace('#\\d+#', '', $modifiers), (int) abs($modifiers));
     }
     if ('mapping' === $context && '"' !== $value[0] && "'" !== $value[0] && '[' !== $value[0] && '{' !== $value[0] && '!' !== $value[0] && false !== strpos($value, ': ')) {
         @trigger_error(sprintf('Using a colon in an unquoted mapping value in line %d is deprecated since Symfony 2.8 and will throw a ParseException in 3.0.', $this->getRealCurrentLineNb() + 1), E_USER_DEPRECATED);
         // to be thrown in 3.0
         // throw new ParseException('A colon cannot be used in an unquoted mapping value.');
     }
     try {
         return Inline::parse($value, $exceptionOnInvalidType, $objectSupport, $objectForMap, $this->refs);
     } catch (ParseException $e) {
         $e->setParsedLine($this->getRealCurrentLineNb() + 1);
         $e->setSnippet($this->currentLine);
         throw $e;
     }
 }
 /**
  * @param NodeInterface $node
  * @param int           $depth
  * @param bool          $prototypedArray
  */
 private function writeNode(NodeInterface $node, $depth = 0, $prototypedArray = false)
 {
     $comments = array();
     $default = '';
     $defaultArray = null;
     $children = null;
     $example = $node->getExample();
     // defaults
     if ($node instanceof ArrayNode) {
         $children = $node->getChildren();
         if ($node instanceof PrototypedArrayNode) {
             $children = $this->getPrototypeChildren($node);
         }
         if (!$children) {
             if ($node->hasDefaultValue() && count($defaultArray = $node->getDefaultValue())) {
                 $default = '';
             } elseif (!is_array($example)) {
                 $default = '[]';
             }
         }
     } elseif ($node instanceof EnumNode) {
         $comments[] = 'One of ' . implode('; ', array_map('json_encode', $node->getValues()));
         $default = $node->hasDefaultValue() ? Inline::dump($node->getDefaultValue()) : '~';
     } else {
         $default = '~';
         if ($node->hasDefaultValue()) {
             $default = $node->getDefaultValue();
             if (is_array($default)) {
                 if (count($defaultArray = $node->getDefaultValue())) {
                     $default = '';
                 } elseif (!is_array($example)) {
                     $default = '[]';
                 }
             } else {
                 $default = Inline::dump($default);
             }
         }
     }
     // required?
     if ($node->isRequired()) {
         $comments[] = 'Required';
     }
     // example
     if ($example && !is_array($example)) {
         $comments[] = 'Example: ' . $example;
     }
     $default = (string) $default != '' ? ' ' . $default : '';
     $comments = count($comments) ? '# ' . implode(', ', $comments) : '';
     $key = $prototypedArray ? '-' : $node->getName() . ':';
     $text = rtrim(sprintf('%-21s%s %s', $key, $default, $comments), ' ');
     if ($info = $node->getInfo()) {
         $this->writeLine('');
         // indenting multi-line info
         $info = str_replace("\n", sprintf("\n%" . $depth * 4 . 's# ', ' '), $info);
         $this->writeLine('# ' . $info, $depth * 4);
     }
     $this->writeLine($text, $depth * 4);
     // output defaults
     if ($defaultArray) {
         $this->writeLine('');
         $message = count($defaultArray) > 1 ? 'Defaults' : 'Default';
         $this->writeLine('# ' . $message . ':', $depth * 4 + 4);
         $this->writeArray($defaultArray, $depth + 1);
     }
     if (is_array($example)) {
         $this->writeLine('');
         $message = count($example) > 1 ? 'Examples' : 'Example';
         $this->writeLine('# ' . $message . ':', $depth * 4 + 4);
         $this->writeArray($example, $depth + 1);
     }
     if ($children) {
         foreach ($children as $childNode) {
             $this->writeNode($childNode, $depth + 1, $node instanceof PrototypedArrayNode && !$node->getKeyAttribute());
         }
     }
 }
Exemple #15
0
 /**
  * Parses a YAML value.
  *
  * @param string $value   A YAML value
  * @param int    $flags   A bit field of PARSE_* constants to customize the YAML parser behavior
  * @param string $context The parser context (either sequence or mapping)
  *
  * @return mixed A PHP value
  *
  * @throws ParseException When reference does not exist
  */
 private function parseValue($value, $flags, $context)
 {
     if (0 === strpos($value, '*')) {
         if (false !== ($pos = strpos($value, '#'))) {
             $value = substr($value, 1, $pos - 2);
         } else {
             $value = substr($value, 1);
         }
         if (!array_key_exists($value, $this->refs)) {
             throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLineNb + 1, $this->currentLine);
         }
         return $this->refs[$value];
     }
     if (preg_match('/^' . self::TAG_PATTERN . self::BLOCK_SCALAR_HEADER_PATTERN . '$/', $value, $matches)) {
         $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
         $data = $this->parseBlockScalar($matches['separator'], preg_replace('#\\d+#', '', $modifiers), (int) abs($modifiers));
         if (isset($matches['tag']) && '!!binary' === $matches['tag']) {
             return Inline::evaluateBinaryScalar($data);
         }
         return $data;
     }
     try {
         $quotation = '' !== $value && ('"' === $value[0] || "'" === $value[0]) ? $value[0] : null;
         // do not take following lines into account when the current line is a quoted single line value
         if (null !== $quotation && preg_match('/^' . $quotation . '.*' . $quotation . '(\\s*#.*)?$/', $value)) {
             return Inline::parse($value, $flags, $this->refs);
         }
         while ($this->moveToNextLine()) {
             // unquoted strings end before the first unindented line
             if (null === $quotation && $this->getCurrentLineIndentation() === 0) {
                 $this->moveToPreviousLine();
                 break;
             }
             $value .= ' ' . trim($this->currentLine);
             // quoted string values end with a line that is terminated with the quotation character
             if ('' !== $this->currentLine && substr($this->currentLine, -1) === $quotation) {
                 break;
             }
         }
         Inline::$parsedLineNumber = $this->getRealCurrentLineNb();
         $parsedValue = Inline::parse($value, $flags, $this->refs);
         if ('mapping' === $context && is_string($parsedValue) && '"' !== $value[0] && "'" !== $value[0] && '[' !== $value[0] && '{' !== $value[0] && '!' !== $value[0] && false !== strpos($parsedValue, ': ')) {
             throw new ParseException('A colon cannot be used in an unquoted mapping value.');
         }
         return $parsedValue;
     } catch (ParseException $e) {
         $e->setParsedLine($this->getRealCurrentLineNb() + 1);
         $e->setSnippet($this->currentLine);
         throw $e;
     }
 }
 /** @HandlerCallback("yml", direction = "serialization") */
 public function serializeToYml(YamlSerializationVisitor $visitor)
 {
     $visitor->writer->writeln(Inline::dump($this->element) . ': ' . Inline::dump($this->value));
 }
Exemple #17
0
 public function testHashStringsResemblingExponentialNumericsShouldNotBeChangedToINF()
 {
     $value = '686e444';
     $this->assertSame($value, Inline::parse(Inline::dump($value)));
 }
Exemple #18
0
 protected function setParameterType(PropertyInterface $parameter, &$raml, $indent)
 {
     $indent = str_repeat(' ', $indent);
     switch (true) {
         case $parameter instanceof Property\IntegerType:
             $raml .= $indent . 'type: integer' . "\n";
             break;
         case $parameter instanceof Property\FloatType:
             $raml .= $indent . 'type: number' . "\n";
             break;
         case $parameter instanceof Property\BooleanType:
             $raml .= $indent . 'type: boolean' . "\n";
             break;
         case $parameter instanceof Property\DateType:
         case $parameter instanceof Property\DateTimeType:
             $raml .= $indent . 'type: date' . "\n";
             break;
         default:
             $raml .= $indent . 'type: string' . "\n";
             break;
     }
     $description = $parameter->getDescription();
     if (!empty($description)) {
         $raml .= $indent . 'description: ' . Inline::dump($parameter->getDescription()) . "\n";
     }
     $raml .= $indent . 'required: ' . ($parameter->isRequired() ? 'true' : 'false') . "\n";
     if ($parameter instanceof Property\DecimalType) {
         $min = $parameter->getMin();
         $max = $parameter->getMax();
         if ($min !== null) {
             $raml .= $indent . 'minimum: ' . $min . "\n";
         }
         if ($max !== null) {
             $raml .= $indent . 'maximum: ' . $max . "\n";
         }
     } elseif ($parameter instanceof Property\StringType) {
         $minLength = $parameter->getMinLength();
         $maxLength = $parameter->getMaxLength();
         $enumeration = $parameter->getEnumeration();
         $pattern = $parameter->getPattern();
         if ($minLength !== null) {
             $raml .= $indent . 'minLength: ' . $minLength . "\n";
         }
         if ($maxLength !== null) {
             $raml .= $indent . 'maxLength: ' . $maxLength . "\n";
         }
         if (!empty($enumeration)) {
             $raml .= $indent . 'enum: ' . Inline::dump($enumeration) . "\n";
         }
         if (!empty($pattern)) {
             $raml .= $indent . 'pattern: ' . Inline::dump($pattern) . "\n";
         }
     }
 }
 private function getParams(array $expectedParams, array $actualParams)
 {
     // Simply use the expectedParams value as default for the missing params.
     if (!$this->io->isInteractive()) {
         return array_replace($expectedParams, $actualParams);
     }
     $isStarted = false;
     foreach ($expectedParams as $key => $message) {
         if (array_key_exists($key, $actualParams)) {
             continue;
         }
         if (!$isStarted) {
             $isStarted = true;
             $this->io->write('<comment>Some parameters are missing. Please provide them.</comment>');
         }
         $default = Inline::dump($message);
         $value = $this->io->ask(sprintf('<question>%s</question> (<comment>%s</comment>): ', $key, $default), $default);
         $actualParams[$key] = Inline::parse($value);
     }
     return $actualParams;
 }
 /**
  * @group legacy
  * @dataProvider getScalarIndicators
  * throws \Symfony\Component\Yaml\Exception\ParseException in 3.0
  */
 public function testParseUnquotedScalarStartingWithScalarIndicator($indicator)
 {
     Inline::parse(sprintf('{ foo: %sfoo }', $indicator));
 }
Exemple #21
0
 /**
  * Parses a YAML value.
  *
  * @param string $value   A YAML value
  * @param int    $flags   A bit field of PARSE_* constants to customize the YAML parser behavior
  * @param string $context The parser context (either sequence or mapping)
  *
  * @return mixed A PHP value
  *
  * @throws ParseException When reference does not exist
  */
 private function parseValue($value, $flags, $context)
 {
     if (0 === strpos($value, '*')) {
         if (false !== ($pos = strpos($value, '#'))) {
             $value = substr($value, 1, $pos - 2);
         } else {
             $value = substr($value, 1);
         }
         if (!array_key_exists($value, $this->refs)) {
             throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLineNb + 1, $this->currentLine);
         }
         return $this->refs[$value];
     }
     if (preg_match('/^' . self::TAG_PATTERN . self::BLOCK_SCALAR_HEADER_PATTERN . '$/', $value, $matches)) {
         $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
         $data = $this->parseBlockScalar($matches['separator'], preg_replace('#\\d+#', '', $modifiers), (int) abs($modifiers));
         if (isset($matches['tag']) && '!!binary' === $matches['tag']) {
             return Inline::evaluateBinaryScalar($data);
         }
         return $data;
     }
     try {
         Inline::$parsedLineNumber = $this->getRealCurrentLineNb();
         $parsedValue = Inline::parse($value, $flags, $this->refs);
         if ('mapping' === $context && is_string($parsedValue) && '"' !== $value[0] && "'" !== $value[0] && '[' !== $value[0] && '{' !== $value[0] && '!' !== $value[0] && false !== strpos($parsedValue, ': ')) {
             throw new ParseException('A colon cannot be used in an unquoted mapping value.');
         }
         return $parsedValue;
     } catch (ParseException $e) {
         $e->setParsedLine($this->getRealCurrentLineNb() + 1);
         $e->setSnippet($this->currentLine);
         throw $e;
     }
 }
Exemple #22
0
 /**
  * Parses a YAML value.
  *
  * @param string  $value                  A YAML value
  * @param bool    $exceptionOnInvalidType True if an exception must be thrown on invalid types false otherwise
  * @param bool    $objectSupport          True if object support is enabled, false otherwise
  *
  * @return mixed  A PHP value
  *
  * @throws ParseException When reference does not exist
  */
 private function parseValue($value, $exceptionOnInvalidType, $objectSupport)
 {
     if (0 === strpos($value, '*')) {
         if (false !== ($pos = strpos($value, '#'))) {
             $value = substr($value, 1, $pos - 2);
         } else {
             $value = substr($value, 1);
         }
         if (!array_key_exists($value, $this->refs)) {
             throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLine);
         }
         return $this->refs[$value];
     }
     if (preg_match('/^' . self::FOLDED_SCALAR_PATTERN . '$/', $value, $matches)) {
         $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
         return $this->parseFoldedScalar($matches['separator'], preg_replace('#\\d+#', '', $modifiers), intval(abs($modifiers)));
     }
     try {
         return Inline::parse($value, $exceptionOnInvalidType, $objectSupport, $this->refs);
     } catch (ParseException $e) {
         $e->setParsedLine($this->getRealCurrentLineNb() + 1);
         $e->setSnippet($this->currentLine);
         throw $e;
     }
 }
Exemple #23
0
 /**
  * @expectedException \Symfony\Component\Yaml\Exception\ParseException
  * @expectedExceptionMessage A reference must contain at least one character.
  */
 public function testParseUnquotedAsteriskFollowedByAComment()
 {
     Inline::parse('{ foo: * #foo }');
 }
Exemple #24
0
 /**
  * Present a node question to the user
  *
  * @param  NodeInterface $node The node in question
  * @param  string $name The name of the node
  * @return mixed The new value of the node
  */
 private function writeNodeQuestion($node, $name)
 {
     if (!$this->questionInfoShown) {
         $this->io->write(array("<comment> ! [NOTE] You can change all the configuration options later", " ! on the config.yml file in the app folder</>\n"));
         $this->questionInfoShown = true;
     }
     if (!$node->getAttribute('asked')) {
         return $node->getDefaultValue();
     }
     $this->writeWarning($node);
     if ($info = $node->getInfo()) {
         $this->io->write(" {$info}");
     }
     if ($example = $node->getExample()) {
         // We use Inline::dump() to convert the value to the YAML
         // format so that it is readable by the user (as an example,
         // false values are converted to 'false' instead of an empty
         // string)
         $example = Inline::dump($example);
         $this->io->write(" Example: <comment>{$example}</comment>");
     }
     $question = " <fg=green>{$name}";
     if ($node instanceof EnumNode) {
         // Create list of possible values for enum configuration parameters
         $values = $node->getValues();
         foreach ($values as &$value) {
             $value = Inline::dump($value);
         }
         $question .= ' (' . implode(', ', $values) . ')';
     }
     $question .= "</fg=green>";
     if ($node->hasDefaultValue()) {
         // Show the default value of the parameter
         $default = Inline::dump($node->getDefaultValue());
         $question .= " [<comment>{$default}</comment>]";
     } else {
         $default = null;
     }
     // Show a user-friendly prompt
     $question .= ":\n > ";
     $value = $this->io->askAndValidate($question, function ($value) use($node) {
         $value = Inline::parse($value);
         // Make sure that there are no errors
         $node->finalize($value);
         return $value;
     }, null, $default);
     $this->io->write("");
     return $value;
 }
Exemple #25
0
 /**
  * @dataProvider getInvalidBinaryData
  */
 public function testParseInvalidBinaryData($data, $expectedMessage)
 {
     $this->setExpectedExceptionRegExp('\\Symfony\\Component\\Yaml\\Exception\\ParseException', $expectedMessage);
     Inline::parse($data);
 }
Exemple #26
0
 /**
  * @dataProvider getDataForIsHash
  */
 public function testIsHash($array, $expected)
 {
     $this->assertSame($expected, Inline::isHash($array));
 }
 public function visitProperty(PropertyMetadata $metadata, $data)
 {
     $v = null === $metadata->getter ? $metadata->reflection->getValue($data) : $data->{$metadata->getter}();
     if (null === $v) {
         return;
     }
     $name = $this->namingStrategy->translateName($metadata);
     $this->writer->writeln(Inline::dump($name) . ':')->indent();
     $this->setCurrentMetadata($metadata);
     $count = $this->writer->changeCount;
     if (null !== ($v = $this->navigator->accept($v, null, $this))) {
         $this->writer->rtrim(false)->writeln(' ' . $v);
     } else {
         if ($count === $this->writer->changeCount) {
             $this->writer->revert();
         }
     }
     $this->writer->outdent();
     $this->revertCurrentMetadata();
 }
 public function serializeDateTimeToYml(YamlSerializationVisitor $visitor, \DateTime $date, array $type)
 {
     return Inline::dump($date->format($this->getFormat($type)));
 }
Exemple #29
0
 /**
  * Parses a YAML value.
  *
  * @param string $value A YAML value
  *
  * @return mixed  A PHP value
  *
  * @throws ParseException When reference does not exist
  */
 private function parseValue($value)
 {
     if (0 === strpos($value, '*')) {
         if (false !== ($pos = strpos($value, '#'))) {
             $value = substr($value, 1, $pos - 2);
         } else {
             $value = substr($value, 1);
         }
         if (!array_key_exists($value, $this->refs)) {
             throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLine);
         }
         return $this->refs[$value];
     }
     if (preg_match('/^(?P<separator>\\||>)(?P<modifiers>\\+|\\-|\\d+|\\+\\d+|\\-\\d+|\\d+\\+|\\d+\\-)?(?P<comments> +#.*)?$/', $value, $matches)) {
         $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
         return $this->parseFoldedScalar($matches['separator'], preg_replace('#\\d+#', '', $modifiers), intval(abs($modifiers)));
     }
     try {
         return Inline::parse($value);
     } catch (ParseException $e) {
         $e->setParsedLine($this->getRealCurrentLineNb() + 1);
         $e->setSnippet($this->currentLine);
         throw $e;
     }
 }
Exemple #30
0
 public function testParseMapReferenceInSequence()
 {
     $foo = array('a' => 'Steve', 'b' => 'Clark', 'c' => 'Brian');
     $this->assertSame(array($foo), Inline::parse('[*foo]', false, false, false, array('foo' => $foo)));
 }