Passed
Branch feature/php7 (3e8a2f)
by Andy
04:54
created

Writer   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 94
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 12
Bugs 0 Features 0
Metric Value
wmc 11
eloc 27
dl 0
loc 94
ccs 0
cts 35
cp 0
rs 10
c 12
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A write() 0 5 1
A getContents() 0 6 1
A setHeaders() 0 9 1
A setData() 0 9 2
A getOpenMode() 0 3 1
A addRow() 0 10 2
A addHeader() 0 9 1
A addRows() 0 4 2
1
<?php
2
3
namespace Palmtree\Csv;
4
5
/**
6
 * Writes an array to a CSV file.
7
 */
8
class Writer extends AbstractCsv
9
{
10
    /** @var array */
11
    private $headers = [];
12
13
    public function getOpenMode(): string
14
    {
15
        return 'w+';
16
    }
17
18
    public static function write($file, $data): void
19
    {
20
        $writer = new static($file);
21
        $writer->setData($data);
22
        $writer->closeDocument();
23
    }
24
25
    /**
26
     * Sets headers and all rows on the CSV file and
27
     * then closes the file handle.
28
     *
29
     * Uses the first row's keys as headers.
30
     */
31
    public function setData(array $data): self
32
    {
33
        if ($this->hasHeaders) {
34
            $this->setHeaders(\array_keys(\reset($data)));
35
        }
36
37
        $this->addRows($data);
38
39
        return $this;
40
    }
41
42
    public function setHeaders(array $headers): self
43
    {
44
        $this->createDocument();
45
46
        $this->headers = $headers;
47
48
        $this->addRow($this->headers);
49
50
        return $this;
51
    }
52
53
    public function addHeader(string $header): self
54
    {
55
        $headers = $this->headers;
56
57
        $headers[] = $header;
58
59
        $this->setHeaders($headers);
60
61
        return $this;
62
    }
63
64
    /**
65
     * Adds multiple rows of data to the CSV file.
66
     */
67
    public function addRows(array $rows): void
68
    {
69
        foreach ($rows as $row) {
70
            $this->addRow($row);
71
        }
72
    }
73
74
    /**
75
     * Adds a row of data to the CSV file.
76
     *
77
     * @param array $row Row of data to add to the file.
78
     *
79
     * @return bool Whether the row was written to the file.
80
     */
81
    public function addRow(array $row): bool
82
    {
83
        $result = $this->getDocument()->fwriteCsv($row);
84
85
        if ($result === false) {
86
            // @todo: handle error
87
            return false;
88
        }
89
90
        return true;
91
    }
92
93
    /**
94
     * @return string
95
     */
96
    public function getContents()
97
    {
98
        $this->getDocument()->trimFinalLineEnding();
99
        $this->getDocument()->fseek(0);
100
101
        return $this->getDocument()->fread($this->getDocument()->getSize());
102
    }
103
}
104