8000 option to dump multi line strings as scalar blocks · symfony/symfony@b438a68 · GitHub
[go: up one dir, main page]

Skip to content

Commit b438a68

Browse files
committed
option to dump multi line strings as scalar blocks
1 parent fce909a commit b438a68

File tree

4 files changed

+40
-0
lines changed

4 files changed

+40
-0
lines changed

src/Symfony/Component/Yaml/Dumper.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,16 @@ public function dump($input, $inline = 0, $indent = 0, $flags = 0)
8484
$isAHash = array_keys($input) !== range(0, count($input) - 1);
8585

8686
foreach ($input as $key => $value) {
87+
if ($inline > 1 && Yaml::DUMP_MULTI_LINE_AS_BLOCK & $flags && is_string($value) && false !== strpos($value, "\n")) {
88+
$output .= sprintf("%s%s%s |\n", $prefix, $isAHash ? Inline::dump($key, $flags).':' : '-', '');
89+
90+
foreach (preg_split('/\n|\r\n/', $value) as $row) {
91+
$output .= sprintf("%s%s%s\n", $prefix, str_repeat(' ', $this->indentation), $row);
92+
}
93+
94+
continue;
95+
}
96+
8797
$willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value);
8898

8999
$output .= sprintf('%s%s%s%s',

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,21 @@ public function objectAsMapProvider()
332332

333333
return $tests;
334334
}
335+
336+
public function testDumpMultiLineStringAsScalarBlock()
337+
{
338+
$data = array(
339+
'data' => array(
340+
'single_line' => 'foo bar baz',
341+
'multi_line' => "foo\nline with trailing spaces:\n \nbar\r\ninteger like line:\n123456789\nempty line:\n\nbaz",
342+
'nested_inlined_multi_line_string' => array(
343+
'inlined_multi_line' => "foo\nbar\r\nempty line:\n\nbaz",
344+
),
345+
),
346+
);
347+
348+
$this->assertSame(file_get_contents(__DIR__.'/Fixtures/multiple_lines_as_literal_block.yml'), $this->dumper->dump($data, 3, 0, Yaml::DUMP_MULTI_LINE_AS_BLOCK));
349+
}
335350
}
336351

337352
class A
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
data:
2+
single_line: 'foo bar baz'
3+
multi_line: |
4+
foo
5+
line with trailing spaces:
6+
7+
bar
8+
integer like line:
9+
123456789
10+
empty line:
11+
12+
baz
13+
nested_inlined_multi_line_string:
14+
inlined_multi_line: "foo\nbar\r\nempty line:\n\nbaz"

src/Symfony/Component/Yaml/Yaml.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ class Yaml
2828
const PARSE_DATETIME = 32;
2929
const DUMP_BASE64_BINARY_DATA = 64;
3030
const DUMP_OBJECT_AS_MAP = 128;
31+
const DUMP_MULTI_LINE_AS_BLOCK = 256;
3132

3233
/**
3334
* Parses YAML into a PHP value.

0 commit comments

Comments
 (0)
0