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

WorksheetManager::getSharedStringsManager()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
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\Style\Style;
15
use Box\Spout\Writer\Common\Entity\Worksheet;
16
use Box\Spout\Writer\Common\Helper\CellHelper;
17
use Box\Spout\Writer\Common\Manager\WorksheetManagerInterface;
18
use Box\Spout\Writer\XLSX\Manager\Style\StyleManager;
19
20
/**
21
 * Class WorksheetManager
22
 * XLSX worksheet manager, providing the interfaces to work with XLSX worksheets.
23
 */
24
class WorksheetManager implements WorksheetManagerInterface
25
{
26
    /**
27
     * Maximum number of characters a cell can contain
28
     * @see https://support.office.com/en-us/article/Excel-specifications-and-limits-16c69c74-3d6a-4aaf-ba35-e6eb276e8eaa [Excel 2007]
29
     * @see https://support.office.com/en-us/article/Excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3 [Excel 2010]
30
     * @see https://support.office.com/en-us/article/Excel-specifications-and-limits-ca36e2dc-1f09-4620-b726-67c00b05040f [Excel 2013/2016]
31
     */
32
    const MAX_CHARACTERS_PER_CELL = 32767;
33
34
    const SHEET_XML_FILE_HEADER = <<<'EOD'
35
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
36
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
37
EOD;
38
39
    /** @var bool Whether inline or shared strings should be used */
40
    protected $shouldUseInlineStrings;
41
42
    /** @var StyleManager Manages styles */
43
    private $styleManager;
44
45
    /** @var SharedStringsManager Helper to write shared strings */
46
    private $sharedStringsManager;
47
48
    /** @var XLSX Strings escaper */
49
    private $stringsEscaper;
50
51
    /** @var StringHelper String helper */
52
    private $stringHelper;
53
54
    /** @var EntityFactory Factory to create entities */
55
    private $entityFactory;
56
57
    /**
58
     * WorksheetManager constructor.
59
     *
60
     * @param OptionsManagerInterface $optionsManager
61
     * @param StyleManager $styleManager
62
     * @param SharedStringsManager $sharedStringsManager
63
     * @param XLSXEscaper $stringsEscaper
64
     * @param StringHelper $stringHelper
65
     * @param EntityFactory $entityFactory
66
     */
67 38
    public function __construct(
68
        OptionsManagerInterface $optionsManager,
69
        StyleManager $styleManager,
70
        SharedStringsManager $sharedStringsManager,
71
        XLSXEscaper $stringsEscaper,
72
        StringHelper $stringHelper,
73
        EntityFactory $entityFactory
74
    ) {
75 38
        $this->shouldUseInlineStrings = $optionsManager->getOption(Options::SHOULD_USE_INLINE_STRINGS);
76 38
        $this->styleManager = $styleManager;
77 38
        $this->sharedStringsManager = $sharedStringsManager;
78 38
        $this->stringsEscaper = $stringsEscaper;
0 ignored issues
show
Documentation Bug introduced by
It seems like $stringsEscaper of type object<Box\Spout\Common\Helper\Escaper\XLSX> is incompatible with the declared type object<Box\Spout\Writer\XLSX\Manager\XLSX> of property $stringsEscaper.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
79 38
        $this->stringHelper = $stringHelper;
80 38
        $this->entityFactory = $entityFactory;
81 38
    }
82
83
    /**
84
     * @return SharedStringsManager
85
     */
86 34
    public function getSharedStringsManager()
87
    {
88 34
        return $this->sharedStringsManager;
89
    }
90
91
    /**
92
     * {@inheritdoc}
93
     */
94 38
    public function startSheet(Worksheet $worksheet)
95
    {
96 38
        $sheetFilePointer = fopen($worksheet->getFilePath(), 'w');
97 38
        $this->throwIfSheetFilePointerIsNotAvailable($sheetFilePointer);
98
99 38
        $worksheet->setFilePointer($sheetFilePointer);
100
101 38
        fwrite($sheetFilePointer, self::SHEET_XML_FILE_HEADER);
102 38
        fwrite($sheetFilePointer, '<sheetData>');
103 38
    }
104
105
    /**
106
     * Checks if the sheet has been sucessfully created. Throws an exception if not.
107
     *
108
     * @param bool|resource $sheetFilePointer Pointer to the sheet data file or FALSE if unable to open the file
109
     * @throws IOException If the sheet data file cannot be opened for writing
110
     * @return void
111
     */
112 38
    private function throwIfSheetFilePointerIsNotAvailable($sheetFilePointer)
113
    {
114 38
        if (!$sheetFilePointer) {
115
            throw new IOException('Unable to open sheet for writing.');
116
        }
117 38
    }
118
119
    /**
120
     * {@inheritdoc}
121
     */
122 30
    public function addRow(Worksheet $worksheet, Row $row)
123
    {
124 30
        if (!$row->isEmpty()) {
125 30
            $this->addNonEmptyRow($worksheet, $row);
126
        }
127
128 29
        $worksheet->setLastWrittenRowIndex($worksheet->getLastWrittenRowIndex() + 1);
129 29
    }
130
131
    /**
132
     * Adds non empty row to the worksheet.
133
     *
134
     * @param Worksheet $worksheet The worksheet to add the row to
135
     * @param Row $row The row to be written
136
     * @throws IOException If the data cannot be written
137
     * @throws InvalidArgumentException If a cell value's type is not supported
138
     * @return void
139
     */
140 30
    private function addNonEmptyRow(Worksheet $worksheet, Row $row)
141
    {
142 30
        $cellNumber = 0;
143 30
        $rowIndex = $worksheet->getLastWrittenRowIndex() + 1;
144 30
        $numCells = count($row->getCells());
145
146 30
        $rowXML = '<row r="' . $rowIndex . '" spans="1:' . $numCells . '">';
147
148
        // @TODO refactoring: move this to its own method
149
        /** @var Cell $cell */
150 30
        foreach ($row->getCells() as $cell) {
151
            // Apply styles - the row style is merged at this point
152 30
            $cell->applyStyle($row->getStyle());
153 30
            $this->styleManager->applyExtraStylesIfNeeded($cell);
154 30
            $registeredStyle = $this->styleManager->registerStyle($cell->getStyle());
155 30
            $rowXML .= $this->getCellXML($rowIndex, $cellNumber, $cell, $registeredStyle->getId());
156 29
            $cellNumber++;
157
        }
158
159 29
        $rowXML .= '</row>';
160
161 29
        $wasWriteSuccessful = fwrite($worksheet->getFilePointer(), $rowXML);
162 29
        if ($wasWriteSuccessful === false) {
163
            throw new IOException("Unable to write data in {$worksheet->getFilePath()}");
164
        }
165 29
    }
166
167
    /**
168
     * Build and return xml for a single cell.
169
     *
170
     * @param int $rowIndex
171
     * @param int $cellNumber
172
     * @param Cell $cell
173
     * @param int $styleId
174
     * @throws InvalidArgumentException If the given value cannot be processed
175
     * @return string
176
     */
177 30
    private function getCellXML($rowIndex, $cellNumber, Cell $cell, $styleId)
178
    {
179 30
        $columnIndex = CellHelper::getCellIndexFromColumnIndex($cellNumber);
180 30
        $cellXML = '<c r="' . $columnIndex . $rowIndex . '"';
181 30
        $cellXML .= ' s="' . $styleId . '"';
182
183 30
        if ($cell->isString()) {
184 29
            $cellXML .= $this->getCellXMLFragmentForNonEmptyString($cell->getValue());
185 4
        } elseif ($cell->isBoolean()) {
186 1
            $cellXML .= ' t="b"><v>' . (int) ($cell->getValue()) . '</v></c>';
187 4
        } elseif ($cell->isNumeric()) {
188 1
            $cellXML .= '><v>' . $cell->getValue() . '</v></c>';
189 4
        } elseif ($cell->isEmpty()) {
190 2
            if ($this->styleManager->shouldApplyStyleOnEmptyCell($styleId)) {
191 1
                $cellXML .= '/>';
192
            } else {
193
                // don't write empty cells that do no need styling
194
                // NOTE: not appending to $cellXML is the right behavior!!
195 2
                $cellXML = '';
196
            }
197
        } else {
198 2
            throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cell->getValue()));
199
        }
200
201 29
        return $cellXML;
202
    }
203
204
    /**
205
     * Returns the XML fragment for a cell containing a non empty string
206
     *
207
     * @param string $cellValue The cell value
208
     * @throws InvalidArgumentException If the string exceeds the maximum number of characters allowed per cell
209
     * @return string The XML fragment representing the cell
210
     */
211 29
    private function getCellXMLFragmentForNonEmptyString($cellValue)
212
    {
213 29
        if ($this->stringHelper->getStringLength($cellValue) > self::MAX_CHARACTERS_PER_CELL) {
214
            throw new InvalidArgumentException('Trying to add a value that exceeds the maximum number of characters allowed in a cell (32,767)');
215
        }
216
217 29
        if ($this->shouldUseInlineStrings) {
218 26
            $cellXMLFragment = ' t="inlineStr"><is><t>' . $this->stringsEscaper->escape($cellValue) . '</t></is></c>';
219
        } else {
220 3
            $sharedStringId = $this->sharedStringsManager->writeString($cellValue);
221 3
            $cellXMLFragment = ' t="s"><v>' . $sharedStringId . '</v></c>';
222
        }
223
224 29
        return $cellXMLFragment;
225
    }
226
227
    /**
228
     * {@inheritdoc}
229
     */
230 34
    public function close(Worksheet $worksheet)
231
    {
232 34
        $worksheetFilePointer = $worksheet->getFilePointer();
233
234 34
        if (!is_resource($worksheetFilePointer)) {
235
            return;
236
        }
237
238 34
        fwrite($worksheetFilePointer, '</sheetData>');
239 34
        fwrite($worksheetFilePointer, '</worksheet>');
240 34
        fclose($worksheetFilePointer);
241 34
    }
242
}
243