Completed
Push — master ( 2fafb6...179ab4 )
by Adrien
02:46
created

Worksheet::addNonEmptyRow()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 3.0032

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 13
cts 14
cp 0.9286
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 12
nc 4
nop 2
crap 3.0032
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 \Box\Spout\Writer\XLSX\Helper\StyleHelper Helper to work with styles */
34
    protected $styleHelper;
35
36
    /** @var bool Whether inline or shared strings should be used */
37
    protected $shouldUseInlineStrings;
38
39
    /** @var \Box\Spout\Common\Escaper\XLSX Strings escaper */
40
    protected $stringsEscaper;
41
42
    /** @var Resource Pointer to the sheet data file (e.g. xl/worksheets/sheet1.xml) */
43
    protected $sheetFilePointer;
44
45
    /** @var int Index of the last written row */
46
    protected $lastWrittenRowIndex = 0;
47
48
    /**
49
     * @param \Box\Spout\Writer\Common\Sheet $externalSheet The associated "external" sheet
50
     * @param string $worksheetFilesFolder Temporary folder where the files to create the XLSX will be stored
51
     * @param \Box\Spout\Writer\XLSX\Helper\SharedStringsHelper $sharedStringsHelper Helper for shared strings
52
     * @param \Box\Spout\Writer\XLSX\Helper\StyleHelper Helper to work with styles
53
     * @param bool $shouldUseInlineStrings Whether inline or shared strings should be used
54
     * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
55
     */
56 126
    public function __construct($externalSheet, $worksheetFilesFolder, $sharedStringsHelper, $styleHelper, $shouldUseInlineStrings)
57
    {
58 126
        $this->externalSheet = $externalSheet;
59 126
        $this->sharedStringsHelper = $sharedStringsHelper;
60 126
        $this->styleHelper = $styleHelper;
61 126
        $this->shouldUseInlineStrings = $shouldUseInlineStrings;
62
63
        /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
64 126
        $this->stringsEscaper = \Box\Spout\Common\Escaper\XLSX::getInstance();
65
66 126
        $this->worksheetFilePath = $worksheetFilesFolder . '/' . strtolower($this->externalSheet->getName()) . '.xml';
67 126
        $this->startSheet();
68 126
    }
69
70
    /**
71
     * Prepares the worksheet to accept data
72
     *
73
     * @return void
74
     * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
75
     */
76 126
    protected function startSheet()
77
    {
78 126
        $this->sheetFilePointer = fopen($this->worksheetFilePath, 'w');
79 126
        $this->throwIfSheetFilePointerIsNotAvailable();
80
81 126
        fwrite($this->sheetFilePointer, self::SHEET_XML_FILE_HEADER);
82 126
        fwrite($this->sheetFilePointer, '<sheetData>');
83 126
    }
84
85
    /**
86
     * Checks if the book has been created. Throws an exception if not created yet.
87
     *
88
     * @return void
89
     * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
90
     */
91 126
    protected function throwIfSheetFilePointerIsNotAvailable()
92
    {
93 126
        if (!$this->sheetFilePointer) {
94
            throw new IOException('Unable to open sheet for writing.');
95
        }
96 126
    }
97
98
    /**
99
     * @return \Box\Spout\Writer\Common\Sheet The "external" sheet
100
     */
101 99
    public function getExternalSheet()
102
    {
103 99
        return $this->externalSheet;
104
    }
105
106
    /**
107
     * @return int The index of the last written row
108
     */
109 90
    public function getLastWrittenRowIndex()
110
    {
111 90
        return $this->lastWrittenRowIndex;
112
    }
113
114
    /**
115
     * @return int The ID of the worksheet
116
     */
117 96
    public function getId()
118
    {
119
        // sheet index is zero-based, while ID is 1-based
120 96
        return $this->externalSheet->getIndex() + 1;
121
    }
122
123
    /**
124
     * Adds data to the worksheet.
125
     *
126
     * @param array $dataRow Array containing data to be written. Cannot be empty.
127
     *          Example $dataRow = ['data1', 1234, null, '', 'data5'];
128
     * @param \Box\Spout\Writer\Style\Style $style Style to be applied to the row. NULL means use default style.
129
     * @return void
130
     * @throws \Box\Spout\Common\Exception\IOException If the data cannot be written
131
     * @throws \Box\Spout\Common\Exception\InvalidArgumentException If a cell value's type is not supported
132
     */
133 90
    public function addRow($dataRow, $style)
134
    {
135 90
        if (!$this->isEmptyRow($dataRow)) {
136 90
            $this->addNonEmptyRow($dataRow, $style);
137 87
        }
138
139 87
        $this->lastWrittenRowIndex++;
140 87
    }
141
142
    /**
143
     * Returns whether the given row is empty
144
     *
145
     * @param array $dataRow Array containing data to be written. Cannot be empty.
146
     *          Example $dataRow = ['data1', 1234, null, '', 'data5'];
147
     * @return bool Whether the given row is empty
148
     */
149 90
    private function isEmptyRow($dataRow)
150
    {
151 90
        $numCells = count($dataRow);
152 90
        return ($numCells === 1 && CellHelper::isEmpty($dataRow[0]));
153
    }
154
155
    /**
156
     * Adds non empty row to the worksheet.
157
     *
158
     * @param array $dataRow Array containing data to be written. Cannot be empty.
159
     *          Example $dataRow = ['data1', 1234, null, '', 'data5'];
160
     * @param \Box\Spout\Writer\Style\Style $style Style to be applied to the row. NULL means use default style.
161
     * @return void
162
     * @throws \Box\Spout\Common\Exception\IOException If the data cannot be written
163
     * @throws \Box\Spout\Common\Exception\InvalidArgumentException If a cell value's type is not supported
164
     */
165 90
    private function addNonEmptyRow($dataRow, $style)
166
    {
167 90
        $cellNumber = 0;
168 90
        $rowIndex = $this->lastWrittenRowIndex + 1;
169 90
        $numCells = count($dataRow);
170
171 90
        $rowXML = '<row r="' . $rowIndex . '" spans="1:' . $numCells . '">';
172
173 90
        foreach($dataRow as $cellValue) {
174 90
            $rowXML .= $this->getCellXML($rowIndex, $cellNumber, $cellValue, $style->getId());
175 87
            $cellNumber++;
176 87
        }
177
178 87
        $rowXML .= '</row>';
179
180 87
        $wasWriteSuccessful = fwrite($this->sheetFilePointer, $rowXML);
181 87
        if ($wasWriteSuccessful === false) {
182
            throw new IOException("Unable to write data in {$this->worksheetFilePath}");
183
        }
184 87
    }
185
186
    /**
187
     * Build and return xml for a single cell.
188
     *
189
     * @param int $rowIndex
190
     * @param int $cellNumber
191
     * @param mixed $cellValue
192
     * @param int $styleId
193
     * @return string
194
     * @throws InvalidArgumentException
195
     */
196 90
    private function getCellXML($rowIndex, $cellNumber, $cellValue, $styleId)
197
    {
198 90
        $columnIndex = CellHelper::getCellIndexFromColumnIndex($cellNumber);
199 90
        $cellXML = '<c r="' . $columnIndex . $rowIndex . '"';
200 90
        $cellXML .= ' s="' . $styleId . '"';
201
202 90
        if (CellHelper::isNonEmptyString($cellValue)) {
203 87
            if ($this->shouldUseInlineStrings) {
204 78
                $cellXML .= ' t="inlineStr"><is><t>' . $this->stringsEscaper->escape($cellValue) . '</t></is></c>';
205 78
            } else {
206 9
                $sharedStringId = $this->sharedStringsHelper->writeString($cellValue);
207 9
                $cellXML .= ' t="s"><v>' . $sharedStringId . '</v></c>';
208
            }
209 90
        } else if (CellHelper::isBoolean($cellValue)) {
210 3
            $cellXML .= ' t="b"><v>' . intval($cellValue) . '</v></c>';
211 12
        } else if (CellHelper::isNumeric($cellValue)) {
212 3
            $cellXML .= '><v>' . $cellValue . '</v></c>';
213 12
        } else if (empty($cellValue)) {
214 6
            if ($this->styleHelper->shouldApplyStyleOnEmptyCell($styleId)) {
215 3
                $cellXML .= '/>';
216 3
            } else {
217
                // don't write empty cells that do no need styling
218
                // NOTE: not appending to $cellXML is the right behavior!!
219 6
                $cellXML = '';
220
            }
221 6
        } else {
222 6
            throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cellValue));
223
        }
224
225 87
        return $cellXML;
226
    }
227
228
    /**
229
     * Closes the worksheet
230
     *
231
     * @return void
232
     */
233 96
    public function close()
234
    {
235 96
        if (!is_resource($this->sheetFilePointer)) {
236
            return;
237
        }
238
239 96
        fwrite($this->sheetFilePointer, '</sheetData>');
240 96
        fwrite($this->sheetFilePointer, '</worksheet>');
241 96
        fclose($this->sheetFilePointer);
242 96
    }
243
}
244