bug #37744 [Yaml] Fix for #36624; Allow PHP constant as first key in block (jnye)

This PR was squashed before being merged into the 3.4 branch.

Discussion
----------

[Yaml] Fix for #36624; Allow PHP constant as first key in block

| Q             | A
| ------------- | ---
| Branch?       | 3.4
| Bug fix?      | yes
| New feature?  | no
| Deprecations? | no
| Tickets       | Fix #36624
| License       | MIT
| Doc PR        |

When using a PHP constant in the first key of a mapping the parser would throw an exception. However if you used a PHP constant in any other key but the first it was allowed. This fix allows PHP constant as the first key.

I've included a test for this parser error along with the fix.

Commits
-------

46f635c492 [Yaml] Fix for #36624; Allow PHP constant as first key in block
This commit is contained in:
Fabien Potencier 2020-08-11 11:42:46 +02:00
commit a77901d6db
2 changed files with 35 additions and 3 deletions

View File

@ -230,8 +230,12 @@ class Parser
$this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(null, true), $flags)
);
} else {
if (isset($values['leadspaces'])
&& self::preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{\[].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $this->trimTag($values['value']), $matches)
if (
isset($values['leadspaces'])
&& (
'!' === $values['value'][0]
|| self::preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{\[].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $this->trimTag($values['value']), $matches)
)
) {
// this is a compact notation element, add to next block and parse
$block = $values['value'];

View File

@ -2025,6 +2025,34 @@ YAML;
$this->assertSame($expected, $this->parser->parse($yaml, Yaml::PARSE_CONSTANT | Yaml::PARSE_KEYS_AS_STRINGS));
}
public function testPhpConstantTagMappingAsScalarKey()
{
$yaml = <<<YAML
map1:
- foo: 'value_0'
!php/const 'Symfony\Component\Yaml\Tests\B::BAR': 'value_1'
map2:
- !php/const 'Symfony\Component\Yaml\Tests\B::FOO': 'value_0'
bar: 'value_1'
YAML;
$this->assertSame([
'map1' => [['foo' => 'value_0', 'bar' => 'value_1']],
'map2' => [['foo' => 'value_0', 'bar' => 'value_1']],
], $this->parser->parse($yaml, Yaml::PARSE_CONSTANT));
}
public function testTagMappingAsScalarKey()
{
$yaml = <<<YAML
map1:
- !!str 0: 'value_0'
!!str 1: 'value_1'
YAML;
$this->assertSame([
'map1' => [['0' => 'value_0', '1' => 'value_1']],
], $this->parser->parse($yaml));
}
public function testMergeKeysWhenMappingsAreParsedAsObjects()
{
$yaml = <<<YAML
@ -2287,7 +2315,7 @@ YAML;
parameters:
abc
# Comment
# Comment
YAML;
$this->assertSame(['parameters' => 'abc'], $this->parser->parse($yaml));