Passed
Push — master ( aa67e9...f960a1 )
by De Cramer
02:31
created

Csv::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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