From 1cc3151cc2499fa28f6738dccdd1de1d5d4445a4 Mon Sep 17 00:00:00 2001 From: Larry Garfield Date: Fri, 2 Aug 2024 09:07:11 -0500 Subject: [PATCH] Escape strings in JSON stream formatter. --- src/Formatter/JsonStreamFormatter.php | 9 +++++++++ tests/JsonStreamFormatterTest.php | 6 ++++++ 2 files changed, 15 insertions(+) diff --git a/src/Formatter/JsonStreamFormatter.php b/src/Formatter/JsonStreamFormatter.php index 872d523..1fd09c0 100644 --- a/src/Formatter/JsonStreamFormatter.php +++ b/src/Formatter/JsonStreamFormatter.php @@ -22,6 +22,15 @@ public function format(): string return 'json-stream'; } + /** + * @param FormatterStream $runningValue + */ + public function serializeString(mixed $runningValue, Field $field, ?string $next): mixed + { + $runningValue->printf('"%s"', is_string($next) ? str_replace('"', '\"', $next) : null); + return $runningValue; + } + /** * @param FormatterStream $runningValue */ diff --git a/tests/JsonStreamFormatterTest.php b/tests/JsonStreamFormatterTest.php index 9d688ec..b07cdf5 100644 --- a/tests/JsonStreamFormatterTest.php +++ b/tests/JsonStreamFormatterTest.php @@ -154,6 +154,12 @@ public static function streamExamples(): iterable ) ]; + yield AllFieldTypes::class . ' with JSON-type characters' => [ + 'data' => new AllFieldTypes( + string: '{ "with quotes", and { characters ".', + ) + ]; + yield NullArrays::class => [ 'data' => new NullArrays(), ];