Completed
Push — master ( d4e57b...3e0afd )
by Adrien
02:47
created

Worksheet::addRow()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 3.0026

Importance

Changes 8
Bugs 1 Features 2
Metric Value
c 8
b 1
f 2
dl 0
loc 23
ccs 14
cts 15
cp 0.9333
rs 9.0856
cc 3
eloc 13
nc 4
nop 2
crap 3.0026
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 120
    public function __construct($externalSheet, $worksheetFilesFolder, $sharedStringsHelper, $styleHelper, $shouldUseInlineStrings)
57
    {
58 120
        $this->externalSheet = $externalSheet;
59 120
        $this->sharedStringsHelper = $sharedStringsHelper;
60 120
        $this->styleHelper = $styleHelper;
61 120
        $this->shouldUseInlineStrings = $shouldUseInlineStrings;
62
63
        /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
64 120
        $this->stringsEscaper = \Box\Spout\Common\Escaper\XLSX::getInstance();
65
66 120
        $this->worksheetFilePath = $worksheetFilesFolder . '/' . strtolower($this->externalSheet->getName()) . '.xml';
67 120
        $this->startSheet();
68 120
    }
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 120
    protected function startSheet()
77
    {
78 120
        $this->sheetFilePointer = fopen($this->worksheetFilePath, 'w');
79 120
        $this->throwIfSheetFilePointerIsNotAvailable();
80
81 120
        fwrite($this->sheetFilePointer, self::SHEET_XML_FILE_HEADER);
82 120
        fwrite($this->sheetFilePointer, '<sheetData>');
83 120
    }
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 120
    protected function throwIfSheetFilePointerIsNotAvailable()
92
    {
93 120
        if (!$this->sheetFilePointer) {
94
            throw new IOException('Unable to open sheet for writing.');
95
        }
96 120
    }
97
98
    /**
99
     * @return \Box\Spout\Writer\Common\Sheet The "external" sheet
100
     */
101 90
    public function getExternalSheet()
102
    {
103 90
        return $this->externalSheet;
104
    }
105
106
    /**
107
     * @return int The index of the last written row
108
     */
109 84
    public function getLastWrittenRowIndex()
110
    {
111 84
        return $this->lastWrittenRowIndex;
112
    }
113
114
    /**
115
     * @return int The ID of the worksheet
116
     */
117 87
    public function getId()
118
    {
119
        // sheet index is zero-based, while ID is 1-based
120 87
        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 84
    public function addRow($dataRow, $style)
134
    {
135 84
        $cellNumber = 0;
136 84
        $rowIndex = $this->lastWrittenRowIndex + 1;
137 84
        $numCells = count($dataRow);
138
139 84
        $rowXML = '<row r="' . $rowIndex . '" spans="1:' . $numCells . '">';
140
141 84
        foreach($dataRow as $cellValue) {
142 84
            $rowXML .= $this->getCellXML($rowIndex, $cellNumber, $cellValue, $style->getId());
143 81
            $cellNumber++;
144 81
        }
145
146 81
        $rowXML .= '</row>';
147
148 81
        $wasWriteSuccessful = fwrite($this->sheetFilePointer, $rowXML);
149 81
        if ($wasWriteSuccessful === false) {
150
            throw new IOException("Unable to write data in {$this->worksheetFilePath}");
151
        }
152
153
        // only update the count if the write worked
154 81
        $this->lastWrittenRowIndex++;
155 81
    }
156
157
    /**
158
     * Build and return xml for a single cell.
159
     *
160
     * @param int $rowIndex
161
     * @param int $cellNumber
162
     * @param mixed $cellValue
163
     * @param int $styleId
164
     * @return string
165
     * @throws InvalidArgumentException
166
     */
167 84
    private function getCellXML($rowIndex, $cellNumber, $cellValue, $styleId)
168
    {
169 84
        $columnIndex = CellHelper::getCellIndexFromColumnIndex($cellNumber);
170 84
        $cellXML = '<c r="' . $columnIndex . $rowIndex . '"';
171 84
        $cellXML .= ' s="' . $styleId . '"';
172
173 84
        if (CellHelper::isNonEmptyString($cellValue)) {
174 81
            if ($this->shouldUseInlineStrings) {
175 72
                $cellXML .= ' t="inlineStr"><is><t>' . $this->stringsEscaper->escape($cellValue) . '</t></is></c>';
176 72
            } else {
177 9
                $sharedStringId = $this->sharedStringsHelper->writeString($cellValue);
178 9
                $cellXML .= ' t="s"><v>' . $sharedStringId . '</v></c>';
179
            }
180 84
        } else if (CellHelper::isBoolean($cellValue)) {
181 3
            $cellXML .= ' t="b"><v>' . intval($cellValue) . '</v></c>';
182 9
        } else if (CellHelper::isNumeric($cellValue)) {
183 3
            $cellXML .= '><v>' . $cellValue . '</v></c>';
184 9
        } else if (empty($cellValue)) {
185 6
            if ($this->styleHelper->shouldApplyStyleOnEmptyCell($styleId)) {
186 3
                $cellXML .= '/>';
187 3
            } else {
188
                // don't write empty cells that do no need styling
189
                // NOTE: not appending to $cellXML is the right behavior!!
190 6
                $cellXML = '';
191
            }
192 6
        } else {
193 3
            throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cellValue));
194
        }
195
196 81
        return $cellXML;
197
    }
198
199
    /**
200
     * Closes the worksheet
201
     *
202
     * @return void
203
     */
204 87
    public function close()
205
    {
206 87
        if (!is_resource($this->sheetFilePointer)) {
207
            return;
208
        }
209
210 87
        fwrite($this->sheetFilePointer, '</sheetData>');
211 87
        fwrite($this->sheetFilePointer, '</worksheet>');
212 87
        fclose($this->sheetFilePointer);
213 87
    }
214
}
215