From 0318bb6a45e0e02eec890a6f5fa6a11fd1a581ac Mon Sep 17 00:00:00 2001 From: zsc <985342160@qq.com> Date: Thu, 17 Oct 2024 13:57:33 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9Ecsv?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- composer.json | 3 ++- src/Encoder/CsvEncoder.php | 47 +++++++++++++++++++++++++++++++++++++ src/Encoder/Factory.php | 5 ++-- src/Encoder/JsonEncoder.php | 1 - 4 files changed, 52 insertions(+), 4 deletions(-) create mode 100644 src/Encoder/CsvEncoder.php diff --git a/composer.json b/composer.json index 6db77d0..8b10f94 100644 --- a/composer.json +++ b/composer.json @@ -17,6 +17,7 @@ "require": { "php": ">=8.1", "guzzlehttp/guzzle": "^7.8", - "symfony/serializer": "^7.1" + "symfony/serializer": "^7.1", + "openspout/openspout": "^4.26" } } diff --git a/src/Encoder/CsvEncoder.php b/src/Encoder/CsvEncoder.php new file mode 100644 index 0000000..b40a22c --- /dev/null +++ b/src/Encoder/CsvEncoder.php @@ -0,0 +1,47 @@ + ',', + ], $defaultContext); + + parent::__construct($context); + } + + public function decode(string $content, array $context = []): array + { + $context = array_merge($this->defaultContext, $context); + + $options = new Options(); + $options->FIELD_DELIMITER = $context['delimiter']; + + $stream = fopen('php://temp', 'r+'); + fwrite($stream, $content); + rewind($stream); + + $reader = new Reader($options); + + $reader->open($stream); + + $rows = []; + + foreach ($reader->getSheetIterator() as $sheet) { + foreach ($sheet->getRowIterator() as $row) { + $rows[] = $row->toArray(); + } + } + + $reader->close(); + fclose($stream); + + return $rows; + } +} \ No newline at end of file diff --git a/src/Encoder/Factory.php b/src/Encoder/Factory.php index afcca11..63ae4b5 100644 --- a/src/Encoder/Factory.php +++ b/src/Encoder/Factory.php @@ -9,6 +9,7 @@ class Factory private static array $map = [ 'json' => JsonEncoder::class, 'xml' => XmlEncoder::class, + 'csv' => CsvEncoder::class, ]; public static function make(string $key): EncoderInterface @@ -26,12 +27,12 @@ public static function make(string $key): EncoderInterface */ public static function makeFromContentType(string $contentType): EncoderInterface { - $key = ''; - if (stripos('xml', $contentType) !== false) { $key = 'xml'; } else if (stripos('json', $contentType) !== false) { $key = 'json'; + } else if (stripos('csv', $contentType) !== false) { + $key = 'csv'; } else { throw new \InvalidArgumentException('Unsupported: ' . $contentType); } diff --git a/src/Encoder/JsonEncoder.php b/src/Encoder/JsonEncoder.php index e4268bc..615b184 100644 --- a/src/Encoder/JsonEncoder.php +++ b/src/Encoder/JsonEncoder.php @@ -2,7 +2,6 @@ namespace Doubler\OpenApiSdk\Encoder; -use Psr\Http\Message\ResponseInterface; use Symfony\Component\Serializer\Encoder\JsonEncoder as SymfonyJsonEncoder; class JsonEncoder extends AbstractEncoder