Skip to content

Commit

Permalink
Merge pull request #102 from mRoca/master
Browse files Browse the repository at this point in the history
Add UTF-8 encoding to CsvWriter
  • Loading branch information
Baachi committed Apr 21, 2015
2 parents c84f6cc + bb09dfc commit cbae2f5
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/Ddeboer/DataImport/Writer/CsvWriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,35 @@ class CsvWriter extends AbstractStreamWriter
{
private $delimiter = ';';
private $enclosure = '"';
private $utf8Encoding = false;

/**
* Constructor
*
* @param string $delimiter The delimiter
* @param string $enclosure The enclosure
* @param resource $stream
* @param bool $utf8Encoding
*/
public function __construct($delimiter = ';', $enclosure = '"', $stream = null)
public function __construct($delimiter = ';', $enclosure = '"', $stream = null, $utf8Encoding = false)
{
parent::__construct($stream);

$this->delimiter = $delimiter;
$this->enclosure = $enclosure;
$this->utf8Encoding = $utf8Encoding;
}

/**
* @inheritdoc
*/
public function prepare()
{
if ($this->utf8Encoding) {
fprintf($this->getStream(), chr(0xEF) . chr(0xBB) . chr(0xBF));
}

return $this;
}

/**
Expand Down
16 changes: 16 additions & 0 deletions tests/Ddeboer/DataImport/Tests/Writer/CsvWriterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ public function testWriteItem()
{
$writer = new CsvWriter(';', '"', $this->getStream());

$writer->prepare();
$writer->writeItem(array('first', 'last'));

$writer
Expand All @@ -29,6 +30,21 @@ public function testWriteItem()
$writer->finish();
}

public function testWriteUtf8Item()
{
$writer = new CsvWriter(';', '"', $this->getStream(), true);

$writer->prepare();
$writer->writeItem(array('Précédent', 'Suivant'));

$this->assertContentsEquals(
chr(0xEF) . chr(0xBB) . chr(0xBF) . "Précédent;Suivant\n",
$writer
);

$writer->finish();
}

public function testFluentInterface()
{
$writer = new CsvWriter(';', '"', $this->getStream());
Expand Down

0 comments on commit cbae2f5

Please sign in to comment.