Skip to content

Commit

Permalink
Merge pull request #102 from holywise/fix-bom-in-all-rows
Browse files Browse the repository at this point in the history
fix bom appears in all rows if _bom is enabled. #101
  • Loading branch information
dereuromark authored Nov 4, 2018
2 parents fa3729e + b4cff01 commit 5ebd2cf
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/View/CsvView.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,13 @@ class CsvView extends View
*/
protected $bomMap;

/**
* BOM first appearance
*
* @var bool
*/
protected $isFirstBom;

/**
* List of special view vars.
*
Expand Down Expand Up @@ -153,6 +160,7 @@ public function __construct(
parent::__construct($request, $response, $eventManager, $viewOptions);

$this->response = $this->response->withType('csv');
$this->isFirstBom = true;
}

/**
Expand Down Expand Up @@ -456,8 +464,9 @@ protected function _generateRow($row = null)
}

//bom must be added after encoding
if ($this->viewVars['_bom']) {
if ($this->viewVars['_bom'] && $this->isFirstBom) {
$csv = $this->getBom($this->viewVars['_csvEncoding']) . $csv;
$this->isFirstBom = false;
}

return $csv;
Expand Down
52 changes: 52 additions & 0 deletions tests/TestCase/View/CsvViewTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,58 @@ public function testBom()
$this->assertSame($expected, $output);
}

/**
* Test BOM appears only in the first row.
*
* @return void
*/
public function testBomMultipleContentRows()
{
if (!extension_loaded('mbstring')) {
$this->markTestSkipped(
'The mbstring extension is not available.'
);
}

$data = [
['test'],
['test2'],
['test3'],
];
$this->view->set(['data' => $data, '_serialize' => 'data', '_bom' => true, '_csvEncoding' => 'UTF-8']);
$output = $this->view->render(false);

$bom = chr(0xEF) . chr(0xBB) . chr(0xBF);
$expected = $bom . 'test' . PHP_EOL . 'test2' . PHP_EOL . 'test3' . PHP_EOL;
$this->assertSame($expected, $output);
}

/**
* Test BOM appears only in the first row even it has a header.
*
* @return void
*/
public function testBomMultipleContentRowsWithHeader()
{
if (!extension_loaded('mbstring')) {
$this->markTestSkipped(
'The mbstring extension is not available.'
);
}

$header = ['column1'];
$data = [
['test'],
['test2'],
];
$this->view->set(['data' => $data, '_header' => $header, '_serialize' => 'data', '_bom' => true, '_csvEncoding' => 'UTF-8']);
$output = $this->view->render(false);

$bom = chr(0xEF) . chr(0xBB) . chr(0xBF);
$expected = $bom . 'column1' . PHP_EOL . 'test' . PHP_EOL . 'test2' . PHP_EOL;
$this->assertSame($expected, $output);
}

/**
* Test render with an array in _serialize
*
Expand Down

0 comments on commit 5ebd2cf

Please sign in to comment.