Skip to content

Commit

Permalink
CO: improve CsvResponse
Browse files Browse the repository at this point in the history
  • Loading branch information
aleeks committed Sep 8, 2017
1 parent 0a03b24 commit 7f40157
Showing 1 changed file with 45 additions and 10 deletions.
55 changes: 45 additions & 10 deletions src/PrestaShopBundle/Component/CsvResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@ class CsvResponse extends StreamedResponse
private $modeType = self::MODE_PAGINATION;

/**
* @var int, default 1 because default modeType is pagination
* @var null|int
*/
private $start = 1;
private $start = null;

/**
* @var int Default limit
Expand All @@ -76,7 +76,7 @@ class CsvResponse extends StreamedResponse
*/
public function __construct($callback = null, $status = 200, $headers = array())
{
parent::__construct(null, $status, $headers);
parent::__construct($callback, $status, $headers);

if (is_null($callback)) {
$this->setCallback(array($this, 'processData'));
Expand Down Expand Up @@ -165,6 +165,8 @@ public function setFileName($fileName)
*/
public function processData()
{
$this->initStart();

if (is_array($this->data)) {
$this->processDataArray();

Expand All @@ -185,21 +187,22 @@ public function processData()
*/
private function processDataArray()
{
$handle = fopen('php://output', 'w+');
$handle = tmpfile();
fputcsv($handle, $this->headersData, ';');

foreach ($this->data as $line) {
fputcsv($handle, $line, ';');
}

fclose($handle);
$this->dumpFile($handle);
}

/**
* Process to data export if $this->data is a callable function
*/
private function processDataCallback()
{
$handle = fopen('php://output', 'w+');
$handle = tmpfile();
fputcsv($handle, $this->headersData, ';');

do {
Expand All @@ -210,8 +213,6 @@ private function processDataCallback()
break;
}

$handle = fopen('php://output', 'w+');

foreach ($data as $line) {
$lineData = array();

Expand All @@ -224,11 +225,29 @@ private function processDataCallback()
fputcsv($handle, $lineData, ';');
}

fclose($handle);

$this->incrementData();

} while ($count === $this->limit);

$this->dumpFile($handle);
}

/**
* Just init $this->start if it is null
*/
private function initStart()
{
if (null !== $this->start) {
return;
}

if (self::MODE_PAGINATION === $this->modeType) {
$this->setStart(1);
}

if (self::MODE_OFFSET === $this->modeType) {
$this->setStart(0);
}
}

/**
Expand All @@ -251,4 +270,20 @@ private function incrementData()

throw new \LogicException('The modeType is not a valid value.');
}

/**
* @param $handle, file pointer
*/
private function dumpFile($handle)
{
fseek($handle, 0);

while (!feof($handle)) {
$buffer = fread($handle, 1024);
echo $buffer;
flush();
}

fclose($handle);
}
}

0 comments on commit 7f40157

Please sign in to comment.