From caf8148fce0e9dfebf42cbae02d00eb3d9f9bcee Mon Sep 17 00:00:00 2001 From: Aaron Piotrowski Date: Fri, 15 Dec 2023 17:46:54 -0600 Subject: [PATCH] Add JsonContent (#355) --- src/BufferedContent.php | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/BufferedContent.php b/src/BufferedContent.php index ae5c66e2..af7dfff9 100644 --- a/src/BufferedContent.php +++ b/src/BufferedContent.php @@ -15,6 +15,23 @@ public static function fromString(string $content, ?string $contentType = null): return new self($content, $contentType); } + /** + * Creates an instance using the given JSON serializable data with the content-type application/json. + * + * @param mixed $json Data which may be JSON serialized with {@see json_encode()}. + */ + public static function fromJson(mixed $json): self + { + try { + return self::fromString(\json_encode($json, flags: \JSON_THROW_ON_ERROR), 'application/json'); + } catch (\JsonException $exception) { + throw new HttpException( + 'Exception thrown encoding JSON content: ' . $exception->getMessage(), + previous: $exception, + ); + } + } + public static function fromFile( string $path, ?string $contentType = null,