Completed
Push — master ( b53068...77007c )
by Freek
01:11 queued 10s
created

SimpleExcelWriter::close()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Spatie\SimpleExcel;
4
5
use Box\Spout\Writer\WriterInterface;
6
use Box\Spout\Common\Entity\Style\Style;
7
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
8
9
class SimpleExcelWriter
10
{
11
    /** @var \Box\Spout\Writer\WriterInterface */
12
    private $writer;
13
14
    private $processHeader = true;
15
16
    private $processingFirstRow = true;
17
18
    private $numberOfRows = 0;
19
20
    public static function create(string $file)
21
    {
22
        return new static($file);
23
    }
24
25
    public function __construct(string $path)
26
    {
27
        $this->writer = WriterEntityFactory::createWriterFromFile($path);
28
29
        $this->writer->openToFile($path);
30
    }
31
32
    public function getWriter(): WriterInterface
33
    {
34
        return $this->writer;
35
    }
36
37
    public function getNumberOfRows(): int
38
    {
39
        return $this->numberOfRows;
40
    }
41
42
    public function noHeaderRow()
43
    {
44
        $this->processHeader = false;
45
46
        return $this;
47
    }
48
49
    /**
50
     * @param \Box\Spout\Common\Entity\Row|array $row
51
     * @param \Box\Spout\Common\Entity\Style\Style|null $style
52
     */
53
    public function addRow($row, Style $style = null)
54
    {
55
        if (is_array($row)) {
56
            if ($this->processHeader && $this->processingFirstRow) {
57
                $this->writeHeaderFromRow($row);
58
            }
59
60
            $row = WriterEntityFactory::createRowFromArray($row, $style);
61
        }
62
63
        $this->writer->addRow($row);
64
        $this->numberOfRows++;
65
66
        $this->processingFirstRow = false;
67
68
        return $this;
69
    }
70
71
    protected function writeHeaderFromRow(array $row)
72
    {
73
        $headerValues = array_keys($row);
74
75
        $headerRow = WriterEntityFactory::createRowFromArray($headerValues);
76
77
        $this->writer->addRow($headerRow);
78
        $this->numberOfRows++;
79
    }
80
81
    public function close()
82
    {
83
        $this->writer->close();
84
    }
85
86
    public function __destruct()
87
    {
88
        $this->close();
89
    }
90
}
91