Created
May 13, 2019 20:16
-
-
Save DanieleGBX/4f22cc6c4cbdbc59af71483363ab65bb to your computer and use it in GitHub Desktop.
Local Packages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"require": { | |
"my-packages/http-responses": "*@dev", | |
}, | |
"repositories": [ | |
{ | |
"type": "path", | |
"url": "./packages/*" | |
} | |
] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "my-packages/http-responses", | |
"type": "library", | |
"description": "Http Responses for Symfony", | |
"autoload": { | |
"psr-4": { "MyPackages\\HttpResponses\\": "src/" } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace MyPackages\HttpResponses; | |
use Symfony\Component\HttpFoundation\Response; | |
class CsvResponse extends Response | |
{ | |
/** @var string */ | |
protected $data; | |
/** @var string */ | |
protected $filename = 'export.csv'; | |
public function __construct($data = [], $status = 200, $headers = []) | |
{ | |
parent::__construct('', $status, $headers); | |
$this->setData($data); | |
} | |
public function setData($data): self | |
{ | |
$this->data = ''; | |
$output = fopen('php://temp', 'r+'); | |
if (0 !== \count($data)) { | |
if (array_keys($data[0]) !== range(0, \count($data[0]) - 1)) { | |
fputcsv($output, array_keys($data[0])); | |
} | |
foreach ($data as $row) { | |
fputcsv($output, $row); | |
} | |
rewind($output); | |
while ($line = fgets($output)) { | |
$this->data .= $line; | |
} | |
} | |
$this->data .= fgets($output); | |
return $this->update(); | |
} | |
public function getFilename(): string | |
{ | |
return $this->filename; | |
} | |
public function setFilename($filename): self | |
{ | |
$this->filename = $filename; | |
return $this->update(); | |
} | |
protected function update(): self | |
{ | |
$this->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $this->filename)); | |
if (!$this->headers->has('Content-Type')) { | |
$this->headers->set('Content-Type', 'text/csv'); | |
} | |
return $this->setContent($this->data); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
__ indicates a subfolder.