Skip to content

Commit

Permalink
Merge pull request #37 from peter279k/optional_headers
Browse files Browse the repository at this point in the history
Add optional parameter headers
  • Loading branch information
jwage authored May 11, 2018
2 parents 7693a63 + c5354f5 commit 41a9449
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/EasyCSV/AbstractBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,25 @@ abstract class AbstractBase
protected $delimiter = ',';
protected $enclosure = '"';

public function __construct($path, $mode = 'r+', $isNeedBOM = false)
public function __construct($path, $mode = 'r+', $isNeedBOM = false, $headers = array())
{
$isNewFile = false;

if (! file_exists($path)) {
touch($path);
$isNewFile = true;
}
$this->handle = new \SplFileObject($path, $mode);
$this->handle->setFlags(\SplFileObject::DROP_NEW_LINE);

if ($isNeedBOM) {
$this->handle->fwrite("\xEF\xBB\xBF");
}

if($isNewFile && isset($headers)) {
$headerLine = join(',', $headers) . PHP_EOL;
$this->handle->fwrite($headerLine, strlen($headerLine));
}
}

public function __destruct()
Expand Down
6 changes: 6 additions & 0 deletions tests/EasyCSV/Tests/WriterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ public function testWriteRow()
$this->assertEquals(18, $this->writer->writeRow('test1, test2, test3'));
}

public function testWriteRowOnHeaders()
{
$writer = new Writer(__DIR__ . '/write.csv', 'r+', false, array('header1', 'header2', 'header3'));
$this->assertEquals(18, $writer->writeRow('test1, test2, test3'));
}

public function testWriteBOMRow()
{
$this->assertEquals(57, $this->writerBOM->writeRow('колонка 1, колонка 2, колонка 3'));
Expand Down

0 comments on commit 41a9449

Please sign in to comment.