From e65638f6f42d81666a3bde2702d72a251df3612b Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Thu, 8 Feb 2018 16:47:44 +0100 Subject: [PATCH] Improvements to printing block strings ref: graphql/graphql-js#f9e67c403a4667372684ee8c3e82e1f0ba27031b --- src/Language/Printer.php | 13 ++++++++++- tests/Language/PrinterTest.php | 40 ++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/src/Language/Printer.php b/src/Language/Printer.php index 25d2a2c..247cf49 100644 --- a/src/Language/Printer.php +++ b/src/Language/Printer.php @@ -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\"\"\""; + } } diff --git a/tests/Language/PrinterTest.php b/tests/Language/PrinterTest.php index a8d0ae2..301abff 100644 --- a/tests/Language/PrinterTest.php +++ b/tests/Language/PrinterTest.php @@ -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 */