Passed
Pull Request — develop_3.0 (#485)
by Adrien
02:47
created

getCellXMLFragmentForNonEmptyString()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 7
cts 8
cp 0.875
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 9
nc 3
nop 1
crap 3.0175
1
<?php
2
3
namespace Box\Spout\Writer\XLSX\Manager;
4
5
use Box\Spout\Common\Exception\InvalidArgumentException;
6
use Box\Spout\Common\Exception\IOException;
7
use Box\Spout\Common\Helper\Escaper\XLSX as XLSXEscaper;
8
use Box\Spout\Common\Helper\StringHelper;
9
use Box\Spout\Common\Manager\OptionsManagerInterface;
10
use Box\Spout\Writer\Common\Creator\EntityFactory;
11
use Box\Spout\Writer\Common\Entity\Cell;
12
use Box\Spout\Writer\Common\Entity\Options;
13
use Box\Spout\Writer\Common\Entity\Row;
14
use Box\Spout\Writer\Common\Entity\Worksheet;
15
use Box\Spout\Writer\Common\Helper\CellHelper;
16
use Box\Spout\Writer\Common\Manager\WorksheetManagerInterface;
17
use Box\Spout\Writer\XLSX\Manager\Style\StyleManager;
18
19
/**
20
 * Class WorksheetManager
21
 * XLSX worksheet manager, providing the interfaces to work with XLSX worksheets.
22
 */
23
class WorksheetManager implements WorksheetManagerInterface
24
{
25
    /**
26
     * Maximum number of characters a cell can contain
27
     * @see https://support.office.com/en-us/article/Excel-specifications-and-limits-16c69c74-3d6a-4aaf-ba35-e6eb276e8eaa [Excel 2007]
28
     * @see https://support.office.com/en-us/article/Excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3 [Excel 2010]
29
     * @see https://support.office.com/en-us/article/Excel-specifications-and-limits-ca36e2dc-1f09-4620-b726-67c00b05040f [Excel 2013/2016]
30
     */
31
    const MAX_CHARACTERS_PER_CELL = 32767;
32
33
    const SHEET_XML_FILE_HEADER = <<<'EOD'
34
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
35
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
36
EOD;
37
38
    /** @var bool Whether inline or shared strings should be used */
39
    protected $shouldUseInlineStrings;
40
41
    /** @var StyleManager Manages styles */
42
    private $styleManager;
43
44
    /** @var SharedStringsManager Helper to write shared strings */
45
    private $sharedStringsManager;
46
47
    /** @var XLSXEscaper Strings escaper */
48
    private $stringsEscaper;
49
50
    /** @var StringHelper String helper */
51
    private $stringHelper;
52
53
    /** @var EntityFactory Factory to create entities */
54
    private $entityFactory;
55
56
    /**
57
     * WorksheetManager constructor.
58
     *
59
     * @param OptionsManagerInterface $optionsManager
60
     * @param StyleManager $styleManager
61
     * @param SharedStringsManager $sharedStringsManager
62
     * @param XLSXEscaper $stringsEscaper
63
     * @param StringHelper $stringHelper
64
     * @param EntityFactory $entityFactory
65
     */
66 38
    public function __construct(
67
        OptionsManagerInterface $optionsManager,
68
        StyleManager $styleManager,
69
        SharedStringsManager $sharedStringsManager,
70
        XLSXEscaper $stringsEscaper,
71
        StringHelper $stringHelper,
72
        EntityFactory $entityFactory
73
    ) {
74 38
        $this->shouldUseInlineStrings = $optionsManager->getOption(Options::SHOULD_USE_INLINE_STRINGS);
75 38
        $this->styleManager = $styleManager;
76 38
        $this->sharedStringsManager = $sharedStringsManager;
77 38
        $this->stringsEscaper = $stringsEscaper;
78 38
        $this->stringHelper = $stringHelper;
79 38
        $this->entityFactory = $entityFactory;
80 38
    }
81
82
    /**
83
     * @return SharedStringsManager
84
     */
85 34
    public function getSharedStringsManager()
86
    {
87 34
        return $this->sharedStringsManager;
88
    }
89
90
    /**
91
     * {@inheritdoc}
92
     */
93 38
    public function startSheet(Worksheet $worksheet)
94
    {
95 38
        $sheetFilePointer = fopen($worksheet->getFilePath(), 'w');
96 38
        $this->throwIfSheetFilePointerIsNotAvailable($sheetFilePointer);
97
98 38
        $worksheet->setFilePointer($sheetFilePointer);
99
100 38
        fwrite($sheetFilePointer, self::SHEET_XML_FILE_HEADER);
101 38
        fwrite($sheetFilePointer, '<sheetData>');
102 38
    }
103
104
    /**
105
     * Checks if the sheet has been sucessfully created. Throws an exception if not.
106
     *
107
     * @param bool|resource $sheetFilePointer Pointer to the sheet data file or FALSE if unable to open the file
108
     * @throws IOException If the sheet data file cannot be opened for writing
109
     * @return void
110
     */
111 38
    private function throwIfSheetFilePointerIsNotAvailable($sheetFilePointer)
112
    {
113 38
        if (!$sheetFilePointer) {
114
            throw new IOException('Unable to open sheet for writing.');
115
        }
116 38
    }
117
118
    /**
119
     * {@inheritdoc}
120
     */
121 30
    public function addRow(Worksheet $worksheet, Row $row)
122
    {
123 30
        if (!$row->isEmpty()) {
124 30
            $this->addNonEmptyRow($worksheet, $row);
125
        }
126
127 29
        $worksheet->setLastWrittenRowIndex($worksheet->getLastWrittenRowIndex() + 1);
128 29
    }
129
130
    /**
131
     * Adds non empty row to the worksheet.
132
     *
133
     * @param Worksheet $worksheet The worksheet to add the row to
134
     * @param Row $row The row to be written
135
     * @throws IOException If the data cannot be written
136
     * @throws InvalidArgumentException If a cell value's type is not supported
137
     * @return void
138
     */
139 30
    private function addNonEmptyRow(Worksheet $worksheet, Row $row)
140
    {
141 30
        $cellNumber = 0;
142 30
        $rowIndex = $worksheet->getLastWrittenRowIndex() + 1;
143 30
        $numCells = count($row->getCells());
144
145 30
        $rowXML = '<row r="' . $rowIndex . '" spans="1:' . $numCells . '">';
146
147
        // @TODO refactoring: move this to its own method
148
        /** @var Cell $cell */
149 30
        foreach ($row->getCells() as $cell) {
150
            // Apply styles - the row style is merged at this point
151 30
            $cell->applyStyle($row->getStyle());
152 30
            $this->styleManager->applyExtraStylesIfNeeded($cell);
153 30
            $registeredStyle = $this->styleManager->registerStyle($cell->getStyle());
154 30
            $rowXML .= $this->getCellXML($rowIndex, $cellNumber, $cell, $registeredStyle->getId());
155 29
            $cellNumber++;
156
        }
157
158 29
        $rowXML .= '</row>';
159
160 29
        $wasWriteSuccessful = fwrite($worksheet->getFilePointer(), $rowXML);
161 29
        if ($wasWriteSuccessful === false) {
162
            throw new IOException("Unable to write data in {$worksheet->getFilePath()}");
163
        }
164 29
    }
165
166
    /**
167
     * Build and return xml for a single cell.
168
     *
169
     * @param int $rowIndex
170
     * @param int $cellNumber
171
     * @param Cell $cell
172
     * @param int $styleId
173
     * @throws InvalidArgumentException If the given value cannot be processed
174
     * @return string
175
     */
176 30
    private function getCellXML($rowIndex, $cellNumber, Cell $cell, $styleId)
177
    {
178 30
        $columnIndex = CellHelper::getCellIndexFromColumnIndex($cellNumber);
179 30
        $cellXML = '<c r="' . $columnIndex . $rowIndex . '"';
180 30
        $cellXML .= ' s="' . $styleId . '"';
181
182 30
        if ($cell->isString()) {
183 29
            $cellXML .= $this->getCellXMLFragmentForNonEmptyString($cell->getValue());
184 4
        } elseif ($cell->isBoolean()) {
185 1
            $cellXML .= ' t="b"><v>' . (int) ($cell->getValue()) . '</v></c>';
186 4
        } elseif ($cell->isNumeric()) {
187 1
            $cellXML .= '><v>' . $cell->getValue() . '</v></c>';
188 4
        } elseif ($cell->isEmpty()) {
189 2
            if ($this->styleManager->shouldApplyStyleOnEmptyCell($styleId)) {
190 1
                $cellXML .= '/>';
191
            } else {
192
                // don't write empty cells that do no need styling
193
                // NOTE: not appending to $cellXML is the right behavior!!
194 2
                $cellXML = '';
195
            }
196
        } else {
197 2
            throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cell->getValue()));
198
        }
199
200 29
        return $cellXML;
201
    }
202
203
    /**
204
     * Returns the XML fragment for a cell containing a non empty string
205
     *
206
     * @param string $cellValue The cell value
207
     * @throws InvalidArgumentException If the string exceeds the maximum number of characters allowed per cell
208
     * @return string The XML fragment representing the cell
209
     */
210 29
    private function getCellXMLFragmentForNonEmptyString($cellValue)
211
    {
212 29
        if ($this->stringHelper->getStringLength($cellValue) > self::MAX_CHARACTERS_PER_CELL) {
213
            throw new InvalidArgumentException('Trying to add a value that exceeds the maximum number of characters allowed in a cell (32,767)');
214
        }
215
216 29
        if ($this->shouldUseInlineStrings) {
217 26
            $cellXMLFragment = ' t="inlineStr"><is><t>' . $this->stringsEscaper->escape($cellValue) . '</t></is></c>';
218
        } else {
219 3
            $sharedStringId = $this->sharedStringsManager->writeString($cellValue);
220 3
            $cellXMLFragment = ' t="s"><v>' . $sharedStringId . '</v></c>';
221
        }
222
223 29
        return $cellXMLFragment;
224
    }
225
226
    /**
227
     * {@inheritdoc}
228
     */
229 34
    public function close(Worksheet $worksheet)
230
    {
231 34
        $worksheetFilePointer = $worksheet->getFilePointer();
232
233 34
        if (!is_resource($worksheetFilePointer)) {
234
            return;
235
        }
236
237 34
        fwrite($worksheetFilePointer, '</sheetData>');
238 34
        fwrite($worksheetFilePointer, '</worksheet>');
239 34
        fclose($worksheetFilePointer);
240 34
    }
241
}
242