Failed Conditions
Push — perf-tests ( 50942d...2fc93e )
by Adrien
14:53
created

Worksheet::addRow()   C

Complexity

Conditions 8
Paths 13

Size

Total Lines 45
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 1 Features 2
Metric Value
c 7
b 1
f 2
dl 0
loc 45
rs 5.3846
cc 8
eloc 30
nc 13
nop 2
1
<?php
2
3
namespace Box\Spout\Writer\XLSX\Internal;
4
5
use Box\Spout\Common\Exception\InvalidArgumentException;
6
use Box\Spout\Common\Exception\IOException;
7
use Box\Spout\Writer\Common\Helper\CellHelper;
8
use Box\Spout\Writer\Common\Internal\WorksheetInterface;
9
10
/**
11
 * Class Worksheet
12
 * Represents a worksheet within a XLSX file. The difference with the Sheet object is
13
 * that this class provides an interface to write data
14
 *
15
 * @package Box\Spout\Writer\XLSX\Internal
16
 */
17
class Worksheet implements WorksheetInterface
18
{
19
    const SHEET_XML_FILE_HEADER = <<<EOD
20
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
21
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
22
EOD;
23
24
    /** @var \Box\Spout\Writer\Common\Sheet The "external" sheet */
25
    protected $externalSheet;
26
27
    /** @var string Path to the XML file that will contain the sheet data */
28
    protected $worksheetFilePath;
29
30
    /** @var \Box\Spout\Writer\XLSX\Helper\SharedStringsHelper Helper to write shared strings */
31
    protected $sharedStringsHelper;
32
33
    /** @var bool Whether inline or shared strings should be used */
34
    protected $shouldUseInlineStrings;
35
36
    /** @var \Box\Spout\Common\Escaper\XLSX Strings escaper */
37
    protected $stringsEscaper;
38
39
    /** @var Resource Pointer to the sheet data file (e.g. xl/worksheets/sheet1.xml) */
40
    protected $sheetFilePointer;
41
42
    /** @var int Index of the last written row */
43
    protected $lastWrittenRowIndex = 0;
44
45
    /**
46
     * @param \Box\Spout\Writer\Common\Sheet $externalSheet The associated "external" sheet
47
     * @param string $worksheetFilesFolder Temporary folder where the files to create the XLSX will be stored
48
     * @param \Box\Spout\Writer\XLSX\Helper\SharedStringsHelper $sharedStringsHelper Helper for shared strings
49
     * @param bool $shouldUseInlineStrings Whether inline or shared strings should be used
50
     * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
51
     */
52
    public function __construct($externalSheet, $worksheetFilesFolder, $sharedStringsHelper, $shouldUseInlineStrings)
53
    {
54
        $this->externalSheet = $externalSheet;
55
        $this->sharedStringsHelper = $sharedStringsHelper;
56
        $this->shouldUseInlineStrings = $shouldUseInlineStrings;
57
58
        /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
59
        $this->stringsEscaper = \Box\Spout\Common\Escaper\XLSX::getInstance();
60
61
        $this->worksheetFilePath = $worksheetFilesFolder . '/' . strtolower($this->externalSheet->getName()) . '.xml';
62
        $this->startSheet();
63
    }
64
65
    /**
66
     * Prepares the worksheet to accept data
67
     *
68
     * @return void
69
     * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
70
     */
71
    protected function startSheet()
72
    {
73
        $this->sheetFilePointer = fopen($this->worksheetFilePath, 'w');
74
        $this->throwIfSheetFilePointerIsNotAvailable();
75
76
        fwrite($this->sheetFilePointer, self::SHEET_XML_FILE_HEADER);
77
        fwrite($this->sheetFilePointer, '<sheetData>');
78
    }
79
80
    /**
81
     * Checks if the book has been created. Throws an exception if not created yet.
82
     *
83
     * @return void
84
     * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
85
     */
86
    protected function throwIfSheetFilePointerIsNotAvailable()
87
    {
88
        if (!$this->sheetFilePointer) {
89
            throw new IOException('Unable to open sheet for writing.');
90
        }
91
    }
92
93
    /**
94
     * @return \Box\Spout\Writer\Common\Sheet The "external" sheet
95
     */
96
    public function getExternalSheet()
97
    {
98
        return $this->externalSheet;
99
    }
100
101
    /**
102
     * @return int The index of the last written row
103
     */
104
    public function getLastWrittenRowIndex()
105
    {
106
        return $this->lastWrittenRowIndex;
107
    }
108
109
    /**
110
     * @return int The ID of the worksheet
111
     */
112
    public function getId()
113
    {
114
        // sheet index is zero-based, while ID is 1-based
115
        return $this->externalSheet->getIndex() + 1;
116
    }
117
118
    /**
119
     * Adds data to the worksheet.
120
     *
121
     * @param array $dataRow Array containing data to be written. Cannot be empty.
122
     *          Example $dataRow = ['data1', 1234, null, '', 'data5'];
123
     * @param \Box\Spout\Writer\Style\Style $style Style to be applied to the row. NULL means use default style.
124
     * @return void
125
     * @throws \Box\Spout\Common\Exception\IOException If the data cannot be written
126
     * @throws \Box\Spout\Common\Exception\InvalidArgumentException If a cell value's type is not supported
127
     */
128
    public function addRow($dataRow, $style)
129
    {
130
        $cellNumber = 0;
131
        $rowIndex = $this->lastWrittenRowIndex + 1;
132
        $numCells = count($dataRow);
133
134
        $rowXML = '<row r="' . $rowIndex . '" spans="1:' . $numCells . '">';
135
136
        foreach($dataRow as $cellValue) {
137
            $columnIndex = CellHelper::getCellIndexFromColumnIndex($cellNumber);
138
            $cellXML = '<c r="' . $columnIndex . $rowIndex . '"';
139
            $cellXML .= ' s="' . $style->getId() . '"';
140
141
            if (CellHelper::isNonEmptyString($cellValue)) {
142
                if ($this->shouldUseInlineStrings) {
143
                    $cellXML .= ' t="inlineStr"><is><t>' . $this->stringsEscaper->escape($cellValue) . '</t></is></c>';
144
                } else {
145
                    $sharedStringId = $this->sharedStringsHelper->writeString($cellValue);
146
                    $cellXML .= ' t="s"><v>' . $sharedStringId . '</v></c>';
147
                }
148
            } else if (CellHelper::isBoolean($cellValue)) {
149
                    $cellXML .= ' t="b"><v>' . intval($cellValue) . '</v></c>';
150
            } else if (CellHelper::isNumeric($cellValue)) {
151
                $cellXML .= '><v>' . $cellValue . '</v></c>';
152
            } else if (empty($cellValue)) {
153
                // don't write empty cells (not appending to $cellXML is the right behavior!)
154
                $cellXML = '';
155
            } else {
156
                throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cellValue));
157
            }
158
159
            $rowXML .= $cellXML;
160
            $cellNumber++;
161
        }
162
163
        $rowXML .= '</row>';
164
165
        $wasWriteSuccessful = fwrite($this->sheetFilePointer, $rowXML);
166
        if ($wasWriteSuccessful === false) {
167
            throw new IOException("Unable to write data in {$this->worksheetFilePath}");
168
        }
169
170
        // only update the count if the write worked
171
        $this->lastWrittenRowIndex++;
172
    }
173
174
    /**
175
     * Closes the worksheet
176
     *
177
     * @return void
178
     */
179
    public function close()
180
    {
181
        if (!is_resource($this->sheetFilePointer)) {
182
            return;
183
        }
184
185
        fwrite($this->sheetFilePointer, '</sheetData>');
186
        fwrite($this->sheetFilePointer, '</worksheet>');
187
        fclose($this->sheetFilePointer);
188
    }
189
}
190