Skip to content

Commit

Permalink
新增csv
Browse files Browse the repository at this point in the history
  • Loading branch information
z985342160 committed Oct 17, 2024
1 parent 2e50b8f commit 0318bb6
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 4 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"require": {
"php": ">=8.1",
"guzzlehttp/guzzle": "^7.8",
"symfony/serializer": "^7.1"
"symfony/serializer": "^7.1",
"openspout/openspout": "^4.26"
}
}
47 changes: 47 additions & 0 deletions src/Encoder/CsvEncoder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

namespace Doubler\OpenApiSdk\Encoder;

use OpenSpout\Reader\CSV\Reader;
use OpenSpout\Reader\CSV\Options;

class CsvEncoder extends AbstractEncoder
{
public function __construct(array $defaultContext = [])
{
$context = array_merge([
'delimiter' => ',',
], $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;
}
}
5 changes: 3 additions & 2 deletions src/Encoder/Factory.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);
}
Expand Down
1 change: 0 additions & 1 deletion src/Encoder/JsonEncoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 0318bb6

Please sign in to comment.