Improvements to printing block strings

ref: graphql/graphql-js#f9e67c403a4667372684ee8c3e82e1f0ba27031b
This commit is contained in:
Daniel Tschinder 2018-02-08 16:47:44 +01:00
parent 8747ff8954
commit e65638f6f4
2 changed files with 52 additions and 1 deletions

View File

@ -140,7 +140,7 @@ class Printer
},
NodeKind::STRING => function(StringValueNode $node) {
if ($node->block) {
return "\"\"\"\n" . str_replace('"""', '\\"""', $node->value) . "\n\"\"\"";
return $this->printBlockString($node->value);
}
return json_encode($node->value);
},
@ -310,4 +310,15 @@ class Printer
)
: '';
}
/**
* Print a block string in the indented block form by adding a leading and
* trailing blank line. However, if a block string starts with whitespace and is
* a single-line, adding a leading blank line would strip that whitespace.
*/
private function printBlockString($value) {
return ($value[0] === ' ' || $value[0] === "\t") && strpos($value, "\n") === false
? '"""' . str_replace('"""', '\\"""', $value) . '"""'
: $this->indent("\"\"\"\n" . str_replace('"""', '\\"""', $value)) . "\n\"\"\"";
}
}

View File

@ -92,6 +92,46 @@ class PrinterTest extends \PHPUnit_Framework_TestCase
$this->assertEquals($expected, Printer::doPrint($mutationAstWithArtifacts));
}
/**
* @it correctly prints single-line block strings with leading space
*/
public function testCorrectlyPrintsSingleLineBlockStringsWithLeadingSpace()
{
$mutationAstWithArtifacts = Parser::parse(
'{ field(arg: """ space-led value""") }'
);
$expected = '{
field(arg: """ space-led value""")
}
';
$this->assertEquals($expected, Printer::doPrint($mutationAstWithArtifacts));
}
/**
* @it correctly prints block strings with a first line indentation
*/
public function testCorrectlyPrintsBlockStringsWithAFirstLineIndentation()
{
$mutationAstWithArtifacts = Parser::parse(
'{
field(arg: """
first
line
indentation
""")
}'
);
$expected = '{
field(arg: """
first
line
indentation
""")
}
';
$this->assertEquals($expected, Printer::doPrint($mutationAstWithArtifacts));
}
/**
* @it prints kitchen sink
*/