Skip to content

Commit 95043b2

Browse files
committed
feature symfony#21114 [Yaml] parse multi-line strings (xabbuh)
This PR was merged into the 3.3-dev branch. Discussion ---------- [Yaml] parse multi-line strings | Q | A | ------------- | --- | Branch? | master | Bug fix? | no | New feature? | yes | BC breaks? | no | Deprecations? | no | Tests pass? | yes | Fixed tickets | | License | MIT | Doc PR | When working on symfony#21084, I discovered that the YAML parser does not support (unquoted) multi-line strings (neither as plain strings nor as values for mappings). This PR adds support for them. Commits ------- ec593b9 [Yaml] parse multi-line strings
2 parents 03d160f + ec593b9 commit 95043b2

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

src/Symfony/Component/Yaml/Parser.php

Lines changed: 36 additions & 0 deletions
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.';

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1465,6 +1465,32 @@ public function testParseMultiLineUnquotedString()
14651465

14661466
$this->assertSame(array('foo' => 'bar baz foobar foo', 'bar' => 'baz'), $this->parser->parse($yaml));
14671467
}
1468+
1469+
public function testParseMultiLineString()
1470+
{
1471+
$this->assertEquals("foo bar\nbaz", $this->parser->parse("foo\nbar\n\nbaz"));
1472+
}
1473+
1474+
public function testParseMultiLineMappingValue()
1475+
{
1476+
$yaml = <<<'EOF'
1477+
foo:
1478+
- bar:
1479+
one
1480+
1481+
two
1482+
three
1483+
EOF;
1484+
$expected = array(
1485+
'foo' => array(
1486+
array(
1487+
'bar' => "one\ntwo three",
1488+
),
1489+
),
1490+
);
1491+
1492+
$this->assertEquals($expected, $this->parser->parse($yaml));
1493+
}
14681494
}
14691495

14701496
class B

0 commit comments

Comments
 (0)