Completed
Push — master ( 4257e9...4984d8 )
by Freek
02:05
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
use Spatie\Macroable\Macroable;
9
10
class SimpleExcelWriter
11
{
12
    use Macroable;
13
14
    /** @var \Box\Spout\Writer\WriterInterface */
15
    private $writer;
16
17
    private $processHeader = true;
18
19
    private $processingFirstRow = true;
20
21
    public static function create(string $file)
22
    {
23
        return new static($file);
24
    }
25
26
    public function __construct(string $path)
27
    {
28
        $this->writer = WriterEntityFactory::createWriterFromFile($path);
29
30
        $this->writer->openToFile($path);
31
    }
32
33
    public function getWriter(): WriterInterface
34
    {
35
        return $this->writer;
36
    }
37
38
    public function noHeaderRow()
39
    {
40
        $this->processHeader = false;
41
42
        return $this;
43
    }
44
45
    /**
46
     * @param \Box\Spout\Common\Entity\Row|array $row
47
     * @param \Box\Spout\Common\Entity\Style\Style|null $style
48
     */
49
    public function addRow($row, Style $style = null)
50
    {
51
        if (is_array($row)) {
52
            if ($this->processHeader && $this->processingFirstRow) {
53
                $this->writeHeaderFromRow($row);
54
            }
55
56
            $row = WriterEntityFactory::createRowFromArray($row, $style);
57
        }
58
59
        $this->writer->addRow($row);
60
61
        $this->processingFirstRow = false;
62
63
        return $this;
64
    }
65
66
    protected function writeHeaderFromRow(array $row)
67
    {
68
        $headerValues = array_keys($row);
69
70
        $headerRow = WriterEntityFactory::createRowFromArray($headerValues);
71
72
        $this->writer->addRow($headerRow);
73
    }
74
75
    public function close()
76
    {
77
        $this->writer->close();
78
    }
79
80
    public function __destruct()
81
    {
82
        $this->close();
83
    }
84
}
85