Skip to content

Commit

Permalink
Merge pull request #5 from ilbee/ilbee-patch-1
Browse files Browse the repository at this point in the history
Update composer.json
  • Loading branch information
ilbee authored Feb 5, 2024
2 parents d2ebdbf + cfaf67a commit 623d135
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 9 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
},
"require": {
"php": ">=7.4 <9",
"symfony/http-foundation": "^4 || ^5 || ^6"
"symfony/http-foundation": "^4 || ^5 || ^6 || ^7"
},
"require-dev": {
"phpunit/phpunit": "^9.6",
Expand Down
17 changes: 10 additions & 7 deletions src/CSVResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

class CSVResponse extends Response
{
private string $fileName = 'CSVExport';
private string $fileName = 'CSVExport.csv';
private ?string $separator = null;

public const COMMA = ',';
Expand All @@ -18,15 +18,20 @@ public function __construct(array $data, ?string $fileName = null, ?string $sepa

$this->separator = $separator;
if ($fileName) {
$this->fileName = $fileName;
$this->setFileName($fileName);
}

$this->setContent($this->initContent($data));
$this->headers->set('Content-Type', 'text/csv');
$this->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $this->fileName));
}

private function initContent($data): string
private function setFileName(string $fileName): void
{
$this->fileName = $fileName;
}

private function initContent(array $data): string
{
$fp = fopen('php://temp', 'w');
foreach ($this->prepareData($data) as $fields) {
Expand Down Expand Up @@ -55,10 +60,8 @@ private function prepareData(array $data): array

$line = [];
foreach ($row as $key => $value) {
if (is_object($value)) {
if (get_class($value) == 'DateTime') {
$value = $value->format('Y-m-d H:i:s');
}
if (is_object($value) && get_class($value) == 'DateTime') {
$value = $value->format('Y-m-d H:i:s');
}
$line[] = $value;
}
Expand Down
2 changes: 1 addition & 1 deletion tests/CSVResponseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public function testResponse(): void
$response->getContent()
);
// Use a comma to separate values.
$response = new CSVResponse($this->getData(), 'my-file-name', CSVResponse::COMMA);
$response = new CSVResponse($this->getData(), 'my-file-name.csv', CSVResponse::COMMA);
$this->assertSame(
"firstName,lastName\nMarcel,TOTO\nMaurice,TATA\n",
$response->getContent()
Expand Down

0 comments on commit 623d135

Please sign in to comment.