Csv::getResource()   A
last analyzed

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
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
ccs 0
cts 0
cp 0
crap 2
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
    public function getResource()
50
    {
51
        $this->init([]);
52
        return parent::getResource();
53
    }
54
55
56
    /**
57
     * Write row data in the csv file.
58
     *
59
     * @param array $rowData data to wrinte in a line of the csv.
60
     */
61
    public function write($rowData) {
62
        $this->init($rowData);
63
64
        fputcsv($this->file, $rowData, $this->delimiter, $this->enclosure, $this->escape);
65
    }
66
67
    /**
68
     * Close the connection and create empty file.
69
     */
70
    public function close()
71
    {
72
        // Create an empty file.
73
        $this->init([]);
74
75
        fclose($this->file);
76
    }
77
78
    /**
79
     * @inheritdoc
80
     */
81
    public function __destruct()
82
    {
83
        $this->close();
84
    }
85
}
86