[Yaml] parse references on merge keys

This commit is contained in:
Christian Flothmann 2017-10-04 00:12:02 +02:00
parent 817f594f48
commit dab72ab9a9
2 changed files with 38 additions and 6 deletions

View File

@ -181,7 +181,7 @@ class Parser
$key = (string) $key;
}
if ('<<' === $key) {
if ('<<' === $key && (!isset($values['value']) || !self::preg_match('#^&(?P<ref>[^ ]+)#u', $values['value'], $refMatches))) {
$mergeNode = true;
$allowOverwrite = true;
if (isset($values['value']) && 0 === strpos($values['value'], '*')) {
@ -226,14 +226,14 @@ class Parser
$data += $parsed; // array union
}
}
} elseif (isset($values['value']) && self::preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#u', $values['value'], $matches)) {
} elseif ('<<' !== $key && isset($values['value']) && self::preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#u', $values['value'], $matches)) {
$isRef = $matches['ref'];
$values['value'] = $matches['value'];
}
if ($mergeNode) {
// Merge keys
} elseif (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) {
} elseif (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#') || '<<' === $key) {
// hash
// if next line is less indented or equal, then it means that the current value is null
if (!$this->isNextLineIndented() && !$this->isNextLineUnIndentedCollection()) {
@ -244,9 +244,13 @@ class Parser
}
} else {
$value = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(), $exceptionOnInvalidType, $objectSupport, $objectForMap);
// Spec: Keys MUST be unique; first one wins.
// But overwriting is allowed when a merge node is used in current block.
if ($allowOverwrite || !isset($data[$key])) {
if ('<<' === $key) {
$this->refs[$refMatches['ref']] = $value;
$data += $value;
} elseif ($allowOverwrite || !isset($data[$key])) {
// Spec: Keys MUST be unique; first one wins.
// But overwriting is allowed when a merge node is used in current block.
$data[$key] = $value;
}
}

View File

@ -1179,6 +1179,34 @@ bar:
YAML;
$this->parser->parse($yaml);
}
public function testParseReferencesOnMergeKeys()
{
$yaml = <<<YAML
mergekeyrefdef:
a: foo
<<: &quux
b: bar
c: baz
mergekeyderef:
d: quux
<<: *quux
YAML;
$expected = array(
'mergekeyrefdef' => array(
'a' => 'foo',
'b' => 'bar',
'c' => 'baz',
),
'mergekeyderef' => array(
'd' => 'quux',
'b' => 'bar',
'c' => 'baz',
),
);
$this->assertSame($expected, $this->parser->parse($yaml));
}
}
class B