Skip to content

Commit

Permalink
option to dump multi line strings as scalar blocks
Browse files Browse the repository at this point in the history
  • Loading branch information
xabbuh committed Mar 1, 2016
1 parent fce909a commit b438a68
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/Symfony/Component/Yaml/Dumper.php
Expand Up @@ -84,6 +84,16 @@ public function dump($input, $inline = 0, $indent = 0, $flags = 0)
$isAHash = array_keys($input) !== range(0, count($input) - 1);

foreach ($input as $key => $value) {
if ($inline > 1 && Yaml::DUMP_MULTI_LINE_AS_BLOCK & $flags && is_string($value) && false !== strpos($value, "\n")) {
$output .= sprintf("%s%s%s |\n", $prefix, $isAHash ? Inline::dump($key, $flags).':' : '-', '');

foreach (preg_split('/\n|\r\n/', $value) as $row) {
$output .= sprintf("%s%s%s\n", $prefix, str_repeat(' ', $this->indentation), $row);
}

continue;
}

$willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value);

$output .= sprintf('%s%s%s%s',
Expand Down
15 changes: 15 additions & 0 deletions src/Symfony/Component/Yaml/Tests/DumperTest.php
Expand Up @@ -332,6 +332,21 @@ public function objectAsMapProvider()

return $tests;
}

public function testDumpMultiLineStringAsScalarBlock()
{
$data = array(
'data' => array(
'single_line' => 'foo bar baz',
'multi_line' => "foo\nline with trailing spaces:\n \nbar\r\ninteger like line:\n123456789\nempty line:\n\nbaz",
'nested_inlined_multi_line_string' => array(
'inlined_multi_line' => "foo\nbar\r\nempty line:\n\nbaz",
),
),
);

$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));
}
}

class A
Expand Down
@@ -0,0 +1,14 @@
data:
single_line: 'foo bar baz'
multi_line: |
foo
line with trailing spaces:
bar
integer like line:
123456789
empty line:
baz
nested_inlined_multi_line_string:
inlined_multi_line: "foo\nbar\r\nempty line:\n\nbaz"
1 change: 1 addition & 0 deletions src/Symfony/Component/Yaml/Yaml.php
Expand Up @@ -28,6 +28,7 @@ class Yaml
const PARSE_DATETIME = 32;
const DUMP_BASE64_BINARY_DATA = 64;
const DUMP_OBJECT_AS_MAP = 128;
const DUMP_MULTI_LINE_AS_BLOCK = 256;

/**
* Parses YAML into a PHP value.
Expand Down

0 comments on commit b438a68

Please sign in to comment.