Completed
Pull Request — master (#302)
by Stefan
03:13
created

Worksheet::getCellXml()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 26
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 6

Importance

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