Skip to content

Commit ec593b9

Browse files
committed
[Yaml] parse multi-line strings
1 parent 64e1da0 commit ec593b9

File tree

2 files changed

+63
-1
lines changed

2 files changed

+63
-1
lines changed

src/Symfony/Component/Yaml/Parser.php

+37-1
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,42 @@ public function parse($value, $flags = 0)
295295
return $value;
296296
}
297297

298+
// try to parse the value as a multi-line string as a last resort
299+
if (0 === $this->currentLineNb) {
300+
$parseError = false;
301+
$previousLineWasNewline = false;
302+
$value = '';
303+
304+
foreach ($this->lines as $line) {
305+
try {
306+
$parsedLine = Inline::parse($line, $flags, $this->refs);
307+
308+
if (!is_string($value)) {
309+
$parseError = true;
310+
break;
311+
}
312+
313+
if ('' === trim($parsedLine)) {
314+
$value .= "\n";
315+
$previousLineWasNewline = true;
316+
} elseif ($previousLineWasNewline) {
317+
$value .= trim($parsedLine);
318+
$previousLineWasNewline = false;
319+
} else {
320+
$value .= ' '.trim($parsedLine);
321+
$previousLineWasNewline = false;
322+
}
323+
} catch (ParseException $e) {
324+
$parseError = true;
325+
break;
326+
}
327+
}
328+
329+
if (!$parseError) {
330+
return trim($value);
331+
}
332+
}
333+
298334
switch (preg_last_error()) {
299335
case PREG_INTERNAL_ERROR:
300336
$error = 'Internal PCRE error.';
@@ -462,7 +498,7 @@ private function getNextEmbedBlock($indentation = null, $inSequence = false)
462498

463499
$previousLineIndentation = $indent;
464500

465-
if ($isItUnindentedCollection && !$this->isStringUnIndentedCollectionItem() && $newIndent === $indent) {
501+
if ($isItUnindentedCollection && !$this->isCurrentLineEmpty() && !$this->isStringUnIndentedCollectionItem() && $newIndent === $indent) {
466502
$this->moveToPreviousLine();
467503
break;
468504
}

src/Symfony/Component/Yaml/Tests/ParserTest.php

+26
Original file line numberDiff line numberDiff line change
@@ -1449,6 +1449,32 @@ public function testParseMultiLineUnquotedString()
14491449

14501450
$this->assertSame(array('foo' => 'bar baz foobar foo', 'bar' => 'baz'), $this->parser->parse($yaml));
14511451
}
1452+
1453+
public function testParseMultiLineString()
1454+
{
1455+
$this->assertEquals("foo bar\nbaz", $this->parser->parse("foo\nbar\n\nbaz"));
1456+
}
1457+
1458+
public function testParseMultiLineMappingValue()
1459+
{
1460+
$yaml = <<<'EOF'
1461+
foo:
1462+
- bar:
1463+
one
1464+
1465+
two
1466+
three
1467+
EOF;
1468+
$expected = array(
1469+
'foo' => array(
1470+
array(
1471+
'bar' => "one\ntwo three",
1472+
),
1473+
),
1474+
);
1475+
1476+
$this->assertEquals($expected, $this->parser->parse($yaml));
1477+
}
14521478
}
14531479

14541480
class B

0 commit comments

Comments
 (0)