Completed
Push — master ( 16eae1...63d154 )
by Freek
01:00
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 $path = '';
15
16
    private $processHeader = true;
17
18
    private $processingFirstRow = true;
19
20
    private $numberOfRows = 0;
21
22
    public static function create(string $file)
23
    {
24
        return new static($file);
25
    }
26
27
    public function __construct(string $path)
28
    {
29
        $this->writer = WriterEntityFactory::createWriterFromFile($path);
30
31
        $this->path = $path;
32
33
        $this->writer->openToFile($this->path);
34
    }
35
36
    public function getPath(): string
37
    {
38
        return $this->path;
39
    }
40
41
    public function getWriter(): WriterInterface
42
    {
43
        return $this->writer;
44
    }
45
46
    public function getNumberOfRows(): int
47
    {
48
        return $this->numberOfRows;
49
    }
50
51
    public function noHeaderRow()
52
    {
53
        $this->processHeader = false;
54
55
        return $this;
56
    }
57
58
    /**
59
     * @param \Box\Spout\Common\Entity\Row|array $row
60
     * @param \Box\Spout\Common\Entity\Style\Style|null $style
61
     */
62
    public function addRow($row, Style $style = null)
63
    {
64
        if (is_array($row)) {
65
            if ($this->processHeader && $this->processingFirstRow) {
66
                $this->writeHeaderFromRow($row);
67
            }
68
69
            $row = WriterEntityFactory::createRowFromArray($row, $style);
70
        }
71
72
        $this->writer->addRow($row);
73
        $this->numberOfRows++;
74
75
        $this->processingFirstRow = false;
76
77
        return $this;
78
    }
79
80
    protected function writeHeaderFromRow(array $row)
81
    {
82
        $headerValues = array_keys($row);
83
84
        $headerRow = WriterEntityFactory::createRowFromArray($headerValues);
85
86
        $this->writer->addRow($headerRow);
87
        $this->numberOfRows++;
88
    }
89
90
    public function close()
91
    {
92
        $this->writer->close();
93
    }
94
95
    public function __destruct()
96
    {
97
        $this->close();
98
    }
99
}
100