Completed
Pull Request — master (#807)
by Adrien
15:11
created

WorksheetManager::getCellXML()   C

Complexity

Conditions 11
Paths 18

Size

Total Lines 51

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 11.2363

Importance

Changes 0
Metric Value
dl 0
loc 51
ccs 7
cts 8
cp 0.875
rs 6.9224
c 0
b 0
f 0
cc 11
nc 18
nop 3
crap 11.2363

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Box\Spout\Writer\ODS\Manager;
4
5
use Box\Spout\Common\Entity\Cell;
6
use Box\Spout\Common\Entity\Row;
7
use Box\Spout\Common\Entity\Style\Style;
8
use Box\Spout\Common\Exception\InvalidArgumentException;
9
use Box\Spout\Common\Exception\IOException;
10
use Box\Spout\Common\Helper\Escaper\ODS as ODSEscaper;
11
use Box\Spout\Common\Helper\StringHelper;
12
use Box\Spout\Writer\Common\Entity\Worksheet;
13
use Box\Spout\Writer\Common\Manager\RegisteredStyle;
14
use Box\Spout\Writer\Common\Manager\Style\StyleMerger;
15
use Box\Spout\Writer\Common\Manager\WorksheetManagerInterface;
16
use Box\Spout\Writer\ODS\Manager\Style\StyleManager;
17
18
/**
19
 * Class WorksheetManager
20
 * ODS worksheet manager, providing the interfaces to work with ODS worksheets.
21
 */
22
class WorksheetManager implements WorksheetManagerInterface
23
{
24
    /** @var \Box\Spout\Common\Helper\Escaper\ODS Strings escaper */
25
    private $stringsEscaper;
26
27
    /** @var StringHelper String helper */
28
    private $stringHelper;
29
30
    /** @var StyleManager Manages styles */
31
    private $styleManager;
32
33
    /** @var StyleMerger Helper to merge styles together */
34
    private $styleMerger;
35
36
    /** @var array Locale info, used for number formatting */
37
    private $localeInfo;
38
39
    /**
40
     * WorksheetManager constructor.
41
     *
42
     * @param StyleManager $styleManager
43 38
     * @param StyleMerger $styleMerger
44
     * @param ODSEscaper $stringsEscaper
45
     * @param StringHelper $stringHelper
46
     */
47
    public function __construct(
48
        StyleManager $styleManager,
49 38
        StyleMerger $styleMerger,
50 38
        ODSEscaper $stringsEscaper,
51 38
        StringHelper $stringHelper
52 38
    ) {
53 38
        $this->styleManager = $styleManager;
54
        $this->styleMerger = $styleMerger;
55
        $this->stringsEscaper = $stringsEscaper;
56
        $this->stringHelper = $stringHelper;
57
        $this->localeInfo = \localeconv();
58
    }
59
60
    /**
61
     * Prepares the worksheet to accept data
62 38
     *
63
     * @param Worksheet $worksheet The worksheet to start
64 38
     * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
65 38
     * @return void
66
     */
67 38
    public function startSheet(Worksheet $worksheet)
68 38
    {
69
        $sheetFilePointer = \fopen($worksheet->getFilePath(), 'w');
70
        $this->throwIfSheetFilePointerIsNotAvailable($sheetFilePointer);
71
72
        $worksheet->setFilePointer($sheetFilePointer);
73
    }
74
75
    /**
76
     * Checks if the sheet has been sucessfully created. Throws an exception if not.
77 38
     *
78
     * @param bool|resource $sheetFilePointer Pointer to the sheet data file or FALSE if unable to open the file
79 38
     * @throws IOException If the sheet data file cannot be opened for writing
80
     * @return void
81
     */
82 38
    private function throwIfSheetFilePointerIsNotAvailable($sheetFilePointer)
83
    {
84
        if (!$sheetFilePointer) {
85
            throw new IOException('Unable to open sheet for writing.');
86
        }
87
    }
88
89
    /**
90 35
     * Returns the table XML root node as string.
91
     *
92 35
     * @param Worksheet $worksheet
93 35
     * @return string <table> node as string
94 35
     */
95
    public function getTableElementStartAsString(Worksheet $worksheet)
96 35
    {
97 35
        $externalSheet = $worksheet->getExternalSheet();
98
        $escapedSheetName = $this->stringsEscaper->escape($externalSheet->getName());
99 35
        $tableStyleName = 'ta' . ($externalSheet->getIndex() + 1);
100
101
        $tableElement = '<table:table table:style-name="' . $tableStyleName . '" table:name="' . $escapedSheetName . '">';
102
        $tableElement .= '<table:table-column table:default-cell-style-name="ce1" table:style-name="co1" table:number-columns-repeated="' . $worksheet->getMaxNumColumns() . '"/>';
103
104
        return $tableElement;
105
    }
106
107
    /**
108
     * Adds a row to the given worksheet.
109
     *
110
     * @param Worksheet $worksheet The worksheet to add the row to
111 33
     * @param Row $row The row to be added
112
     * @throws InvalidArgumentException If a cell value's type is not supported
113 33
     * @throws IOException If the data cannot be written
114 33
     * @return void
115
     */
116 33
    public function addRow(Worksheet $worksheet, Row $row)
117
    {
118 33
        $cells = $row->getCells();
119 33
        $rowStyle = $row->getStyle();
120
121 33
        $data = '<table:table-row table:style-name="ro1">';
122
123 33
        $currentCellIndex = 0;
124
        $nextCellIndex = 1;
125 33
126
        for ($i = 0; $i < $row->getNumCells(); $i++) {
127 33
            /** @var Cell $cell */
128 33
            $cell = $cells[$currentCellIndex];
129 32
            /** @var Cell|null $nextCell */
130
            $nextCell = isset($cells[$nextCellIndex]) ? $cells[$nextCellIndex] : null;
131
132 32
            if ($nextCell === null || $cell->getValue() !== $nextCell->getValue()) {
133
                $registeredStyle = $this->applyStyleAndRegister($cell, $rowStyle);
134
                $cellStyle = $registeredStyle->getStyle();
135 32
                if ($registeredStyle->isMatchingRowStyle()) {
136
                    $rowStyle = $cellStyle; // Replace actual rowStyle (possibly with null id) by registered style (with id)
137 32
                }
138 32
139
                $data .= $this->getCellXMLWithStyle($cell, $cellStyle, $currentCellIndex, $nextCellIndex);
140
                $currentCellIndex = $nextCellIndex;
141
            }
142
143 32
            $nextCellIndex++;
144 32
        }
145 32
146
        $data .= '</table:table-row>';
147
148
        $wasWriteSuccessful = \fwrite($worksheet->getFilePointer(), $data);
149
        if ($wasWriteSuccessful === false) {
150
            throw new IOException("Unable to write data in {$worksheet->getFilePath()}");
151
        }
152
153
        // only update the count if the write worked
154
        $lastWrittenRowIndex = $worksheet->getLastWrittenRowIndex();
155
        $worksheet->setLastWrittenRowIndex($lastWrittenRowIndex + 1);
156
    }
157
158 33
    /**
159
     * Applies styles to the given style, merging the cell's style with its row's style
160
     *
161 33
     * @param Cell $cell
162 33
     * @param Style $rowStyle
163 33
     * @throws InvalidArgumentException If a cell value's type is not supported
164
     * @return RegisteredStyle
165 33
     */
166 33
    private function applyStyleAndRegister(Cell $cell, Style $rowStyle) : RegisteredStyle
167
    {
168 33
        $isMatchingRowStyle = false;
169
        if ($cell->getStyle()->isEmpty()) {
170 33
            $cell->setStyle($rowStyle);
171
172
            $possiblyUpdatedStyle = $this->styleManager->applyExtraStylesIfNeeded($cell);
173
174
            if ($possiblyUpdatedStyle->isUpdated()) {
175
                $registeredStyle = $this->styleManager->registerStyle($possiblyUpdatedStyle->getStyle());
176
            } else {
177
                $registeredStyle = $this->styleManager->registerStyle($rowStyle);
178
                $isMatchingRowStyle = true;
179
            }
180
        } else {
181
            $mergedCellAndRowStyle = $this->styleMerger->merge($cell->getStyle(), $rowStyle);
182 33
            $cell->setStyle($mergedCellAndRowStyle);
183
184 33
            $possiblyUpdatedStyle = $this->styleManager->applyExtraStylesIfNeeded($cell);
185
            if ($possiblyUpdatedStyle->isUpdated()) {
186 33
                $newCellStyle = $possiblyUpdatedStyle->getStyle();
187 4
            } else {
188
                $newCellStyle = $mergedCellAndRowStyle;
189
            }
190 33
191 28
            $registeredStyle = $this->styleManager->registerStyle($newCellStyle);
192
        }
193 28
194 28
        return new RegisteredStyle($registeredStyle, $isMatchingRowStyle);
195 28
    }
196
197
    private function getCellXMLWithStyle(Cell $cell, Style $style, int $currentCellIndex, int $nextCellIndex) : string
198 28
    {
199 7
        $styleIndex = $style->getId() + 1; // 1-based
200 2
201 2
        $numTimesValueRepeated = ($nextCellIndex - $currentCellIndex);
202 2
203 2
        return $this->getCellXML($cell, $styleIndex, $numTimesValueRepeated);
204 6
    }
205 2
206 2
    /**
207 2
     * Returns the cell XML content, given its value.
208 5
     *
209
     * @param Cell $cell The cell to be written
210 1
     * @param int $styleIndex Index of the used style
211 1
     * @param int $numTimesValueRepeated Number of times the value is consecutively repeated
212 1
     * @throws InvalidArgumentException If a cell value's type is not supported
213 4
     * @return string The cell XML content
214 2
     */
215
    private function getCellXML(Cell $cell, $styleIndex, $numTimesValueRepeated)
216 2
    {
217
        $data = '<table:table-cell table:style-name="ce' . $styleIndex . '"';
218
219 32
        if ($numTimesValueRepeated !== 1) {
220
            $data .= ' table:number-columns-repeated="' . $numTimesValueRepeated . '"';
221
        }
222
223
        if ($cell->isString()) {
224
            $data .= ' office:value-type="string" calcext:value-type="string">';
225
226
            $cellValueLines = \explode("\n", $cell->getValue());
227
            foreach ($cellValueLines as $cellValueLine) {
228 35
                $data .= '<text:p>' . $this->stringsEscaper->escape($cellValueLine) . '</text:p>';
229
            }
230 35
231
            $data .= '</table:table-cell>';
232 35
        } elseif ($cell->isBoolean()) {
233
            $value = $cell->getValue() ? 'true' : 'false'; // boolean-value spec: http://docs.oasis-open.org/office/v1.2/os/OpenDocument-v1.2-os-part1.html#datatype-boolean
234
            $data .= ' office:value-type="boolean" calcext:value-type="boolean" office:boolean-value="' . $value . '">';
235
            $data .= '<text:p>' . $cell->getValue() . '</text:p>';
236 35
            $data .= '</table:table-cell>';
237 35
        } elseif ($cell->isNumeric()) {
238
            $cellValue = $cell->getValue();
239
            // Formatting of float values is locale dependent. Thousands separators and decimal points
240
            // vary from locale to locale (en_US: 12.34 vs pl_PL: 12,34). However, ODS values must
241
            // be formatted with no thousands separator and a "." as decimal point to work properly.
242
            // We must then convert the value to the correct format before storing it.
243
            if (is_float($cellValue)) {
244
                $cellValue = str_replace(
245
                    [$this->localeInfo['thousands_sep'], $this->localeInfo['decimal_point']],
246
                    ['', '.'],
247
                    $cellValue
248
                );
249
            }
250
            $data .= ' office:value-type="float" calcext:value-type="float" office:value="' . $cellValue . '">';
251
            $data .= '<text:p>' . $cellValue . '</text:p>';
252
            $data .= '</table:table-cell>';
253
        } elseif ($cell->isError() && is_string($cell->getValueEvenIfError())) {
254
            // only writes the error value if it's a string
255
            $data .= ' office:value-type="string" calcext:value-type="error" office:value="">';
256
            $data .= '<text:p>' . $cell->getValueEvenIfError() . '</text:p>';
257
            $data .= '</table:table-cell>';
258
        } elseif ($cell->isEmpty()) {
259
            $data .= '/>';
260
        } else {
261
            throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . \gettype($cell->getValue()));
262
        }
263
264
        return $data;
265
    }
266
267
    /**
268
     * Closes the worksheet
269
     *
270
     * @param Worksheet $worksheet
271
     * @return void
272
     */
273
    public function close(Worksheet $worksheet)
274
    {
275
        $worksheetFilePointer = $worksheet->getFilePointer();
276
277
        if (!\is_resource($worksheetFilePointer)) {
278
            return;
279
        }
280
281
        \fclose($worksheetFilePointer);
282
    }
283
}
284