1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Oliverde8\Component\PhpEtl\Model\File\Csv; |
4
|
|
|
|
5
|
|
|
use Oliverde8\Component\PhpEtl\Model\File\AbstractFile; |
6
|
|
|
use Oliverde8\Component\PhpEtl\Model\File\FileWriterInterface; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Class Writer |
10
|
|
|
* |
11
|
|
|
* @author de Cramer Oliver<[email protected]> |
12
|
|
|
* @copyright 2018 Oliverde8 |
13
|
|
|
* @package Oliverde8\Component\PhpEtl\Model\File\Csv |
14
|
|
|
*/ |
15
|
|
|
class Writer extends AbstractFile implements FileWriterInterface |
16
|
|
|
{ |
17
|
|
|
/** @var bool */ |
18
|
|
|
protected $hasHeader; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Writer constructor. |
22
|
|
|
* |
23
|
|
|
* @param $filePath |
24
|
|
|
* @param bool $hasHeaders |
25
|
|
|
* @param string $delimiter |
26
|
|
|
* @param string $enclosure |
27
|
|
|
* @param string $escape |
28
|
|
|
*/ |
29
|
|
|
public function __construct($filePath, $hasHeaders = true, $delimiter = ';', $enclosure = '"', $escape = '\\') |
30
|
|
|
{ |
31
|
|
|
$this->hasHeader = $hasHeaders; |
32
|
|
|
parent::__construct($filePath, $delimiter, $enclosure, $escape); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Initialize the write of the file. |
38
|
|
|
*/ |
39
|
|
|
protected function init($rowData) |
40
|
|
|
{ |
41
|
|
|
if (is_null($this->file)) { |
|
|
|
|
42
|
|
|
$this->file = fopen($this->filePath, 'w'); |
43
|
|
|
|
44
|
|
|
if ($this->hasHeader) { |
45
|
|
|
fputcsv($this->file, array_keys($rowData), $this->delimiter, $this->enclosure, $this->escape); |
46
|
|
|
} |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Write row data in the csv file. |
52
|
|
|
* |
53
|
|
|
* @param array $rowData data to wrinte in a line of the csv. |
54
|
|
|
*/ |
55
|
|
|
public function write($rowData) { |
56
|
|
|
$this->init($rowData); |
57
|
|
|
|
58
|
|
|
fputcsv($this->file, $rowData, $this->delimiter, $this->enclosure, $this->escape); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Close the connection and create empty file. |
63
|
|
|
*/ |
64
|
|
|
public function close() |
65
|
|
|
{ |
66
|
|
|
// Create an empty file. |
67
|
|
|
$this->init([]); |
68
|
|
|
|
69
|
|
|
fclose($this->file); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @inheritdoc |
74
|
|
|
*/ |
75
|
|
|
public function __destruct() |
76
|
|
|
{ |
77
|
|
|
$this->close(); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|