diff --git a/lib/EasyCSV/AbstractBase.php b/lib/EasyCSV/AbstractBase.php index 30b21a0..37bc38c 100644 --- a/lib/EasyCSV/AbstractBase.php +++ b/lib/EasyCSV/AbstractBase.php @@ -8,10 +8,13 @@ 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); @@ -19,6 +22,11 @@ public function __construct($path, $mode = 'r+', $isNeedBOM = false) 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() diff --git a/tests/EasyCSV/Tests/WriterTest.php b/tests/EasyCSV/Tests/WriterTest.php index a49fe54..8f0c4b4 100644 --- a/tests/EasyCSV/Tests/WriterTest.php +++ b/tests/EasyCSV/Tests/WriterTest.php @@ -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'));