From 28ce18f8f0d218fc06823446d208e73085010239 Mon Sep 17 00:00:00 2001 From: Matias Griese Date: Wed, 1 Jul 2020 14:51:27 +0300 Subject: [PATCH] Improved `CvsFormatter` to attempt to encode non-scalar variables into JSON before giving up --- CHANGELOG.md | 2 ++ .../Grav/Framework/File/Formatter/CsvFormatter.php | 13 +++++++++++++ 2 files changed, 15 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 392a772e6..65f5e2840 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ 1. [](#new) * Added new `onAfterCacheClear` event +1. [](#improved) + * Improved `CvsFormatter` to attempt to encode non-scalar variables into JSON before giving up 1. [](#bugfix) * Fixed `MediaUploadTrait::copyUploadedFile()` not adding uploaded media to the collection * Fixed regression in saving media to a new Flex Object [admin#1867](https://github.com/getgrav/grav-plugin-admin/issues/1867) diff --git a/system/src/Grav/Framework/File/Formatter/CsvFormatter.php b/system/src/Grav/Framework/File/Formatter/CsvFormatter.php index 3319623f1..29a5c2d30 100644 --- a/system/src/Grav/Framework/File/Formatter/CsvFormatter.php +++ b/system/src/Grav/Framework/File/Formatter/CsvFormatter.php @@ -123,6 +123,19 @@ class CsvFormatter extends AbstractFormatter protected function encodeLine(array $line, string $delimiter): string { foreach ($line as $key => &$value) { + // Oops, we need to convert the line to a string. + if (!\is_scalar($value)) { + if (is_array($value) || $value instanceof \JsonSerializable || $value instanceof \stdClass) { + $value = json_encode($value); + } elseif (is_object($value)) { + if (method_exists($value, 'toJson')) { + $value = $value->toJson(); + } elseif (method_exists($value, 'toArray')) { + $value = json_encode($value->toArray()); + } + } + } + $value = $this->escape((string)$value); } unset($value);