Passed
Pull Request — develop_3.0 (#495)
by Adrien
02:45
created

WorksheetManager::startSheet()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Box\Spout\Writer\ODS\Manager;
4
5
use Box\Spout\Common\Exception\InvalidArgumentException;
6
use Box\Spout\Common\Exception\IOException;
7
use Box\Spout\Common\Helper\Escaper\ODS as ODSEscaper;
8
use Box\Spout\Common\Helper\StringHelper;
9
use Box\Spout\Writer\Common\Entity\Cell;
10
use Box\Spout\Writer\Common\Entity\Row;
11
use Box\Spout\Writer\Common\Entity\Style\Style;
12
use Box\Spout\Writer\Common\Entity\Worksheet;
13
use Box\Spout\Writer\Common\Manager\Style\StyleMerger;
14
use Box\Spout\Writer\Common\Manager\WorksheetManagerInterface;
15
use Box\Spout\Writer\ODS\Manager\Style\StyleManager;
16
17
/**
18
 * Class WorksheetManager
19
 * ODS worksheet manager, providing the interfaces to work with ODS worksheets.
20
 */
21
class WorksheetManager implements WorksheetManagerInterface
22
{
23
    /** @var \Box\Spout\Common\Helper\Escaper\ODS Strings escaper */
24
    private $stringsEscaper;
25
26
    /** @var StringHelper String helper */
27
    private $stringHelper;
28
29
    /** @var StyleManager Manages styles */
30
    private $styleManager;
31
32
    /** @var StyleManager Helper to merge styles together */
33
    private $styleMerger;
34
35
    /**
36
     * WorksheetManager constructor.
37
     *
38
     * @param StyleManager $styleManager
39
     * @param StyleMerger $styleMerger
40
     * @param ODSEscaper $stringsEscaper
41
     * @param StringHelper $stringHelper
42
     */
43 36
    public function __construct(
44
        StyleManager $styleManager,
45
        StyleMerger $styleMerger,
46
        ODSEscaper $stringsEscaper,
47
        StringHelper $stringHelper
48
    ) {
49 36
        $this->styleManager = $styleManager;
50 36
        $this->styleMerger = $styleMerger;
0 ignored issues
show
Documentation Bug introduced by
It seems like $styleMerger of type object<Box\Spout\Writer\...ager\Style\StyleMerger> is incompatible with the declared type object<Box\Spout\Writer\...ger\Style\StyleManager> of property $styleMerger.

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...
51 36
        $this->stringsEscaper = $stringsEscaper;
52 36
        $this->stringHelper = $stringHelper;
53 36
    }
54
55
    /**
56
     * Prepares the worksheet to accept data
57
     *
58
     * @param Worksheet $worksheet The worksheet to start
59
     * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
60
     * @return void
61
     */
62 36
    public function startSheet(Worksheet $worksheet)
63
    {
64 36
        $sheetFilePointer = fopen($worksheet->getFilePath(), 'w');
65 36
        $this->throwIfSheetFilePointerIsNotAvailable($sheetFilePointer);
66
67 36
        $worksheet->setFilePointer($sheetFilePointer);
68 36
    }
69
70
    /**
71
     * Checks if the sheet has been sucessfully created. Throws an exception if not.
72
     *
73
     * @param bool|resource $sheetFilePointer Pointer to the sheet data file or FALSE if unable to open the file
74
     * @throws IOException If the sheet data file cannot be opened for writing
75
     * @return void
76
     */
77 36
    private function throwIfSheetFilePointerIsNotAvailable($sheetFilePointer)
78
    {
79 36
        if (!$sheetFilePointer) {
80
            throw new IOException('Unable to open sheet for writing.');
81
        }
82 36
    }
83
84
    /**
85
     * Returns the table XML root node as string.
86
     *
87
     * @param Worksheet $worksheet
88
     * @return string <table> node as string
89
     */
90 33
    public function getTableElementStartAsString(Worksheet $worksheet)
91
    {
92 33
        $externalSheet = $worksheet->getExternalSheet();
93 33
        $escapedSheetName = $this->stringsEscaper->escape($externalSheet->getName());
94 33
        $tableStyleName = 'ta' . ($externalSheet->getIndex() + 1);
95
96 33
        $tableElement  = '<table:table table:style-name="' . $tableStyleName . '" table:name="' . $escapedSheetName . '">';
97 33
        $tableElement .= '<table:table-column table:default-cell-style-name="ce1" table:style-name="co1" table:number-columns-repeated="' . $worksheet->getMaxNumColumns() . '"/>';
98
99 33
        return $tableElement;
100
    }
101
102
    /**
103
     * Adds a row to the given worksheet.
104
     *
105
     * @param Worksheet $worksheet The worksheet to add the row to
106
     * @param Row $row The row to be added
107
     * @throws IOException If the data cannot be written
108
     * @throws InvalidArgumentException If a cell value's type is not supported
109
     * @return void
110
     */
111 30
    public function addRow(Worksheet $worksheet, Row $row)
112
    {
113 30
        $cells = $row->getCells();
114 30
        $cellsCount = count($cells);
115 30
        $rowStyle = $row->getStyle();
116
117 30
        $data = '<table:table-row table:style-name="ro1">';
118
119 30
        $currentCellIndex = 0;
120 30
        $nextCellIndex = 1;
121
122 30
        for ($i = 0; $i < $cellsCount; $i++) {
123
            /** @var Cell $cell */
124 30
            $cell = $cells[$currentCellIndex];
125
            /** @var Cell|null $nextCell */
126 30
            $nextCell = isset($cells[$nextCellIndex]) ? $cells[$nextCellIndex] : null;
127
128 30
            if ($nextCell === null || $cell->getValue() !== $nextCell->getValue()) {
129 30
                $data .= $this->applyStyleAndGetCellXML($cell, $rowStyle, $currentCellIndex, $nextCellIndex);
130 29
                $currentCellIndex = $nextCellIndex;
131
            }
132
133 29
            $nextCellIndex++;
134
        }
135
136 29
        $data .= '</table:table-row>';
137
138 29
        $wasWriteSuccessful = fwrite($worksheet->getFilePointer(), $data);
139 29
        if ($wasWriteSuccessful === false) {
140
            throw new IOException("Unable to write data in {$worksheet->getFilePath()}");
141
        }
142
143
        // only update the count if the write worked
144 29
        $lastWrittenRowIndex = $worksheet->getLastWrittenRowIndex();
145 29
        $worksheet->setLastWrittenRowIndex($lastWrittenRowIndex + 1);
146 29
    }
147
148
    /**
149
     * Applies styles to the given style, merging the cell's style with its row's style
150
     * Then builds and returns xml for the cell.
151
     *
152
     * @param Cell $cell
153
     * @param Style $rowStyle
154
     * @param int $currentCellIndex
155
     * @param int $nextCellIndex
156
     * @throws InvalidArgumentException If a cell value's type is not supported
157
     * @return string
158
     */
159 30
    private function applyStyleAndGetCellXML(Cell $cell, Style $rowStyle, $currentCellIndex, $nextCellIndex)
160
    {
161
        // Apply row and extra styles
162 30
        $mergedCellAndRowStyle = $this->styleMerger->merge($cell->getStyle(), $rowStyle);
0 ignored issues
show
Bug introduced by
The method merge() does not seem to exist on object<Box\Spout\Writer\...ger\Style\StyleManager>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
163 30
        $cell->setStyle($mergedCellAndRowStyle);
164 30
        $newCellStyle = $this->styleManager->applyExtraStylesIfNeeded($cell);
165
166 30
        $registeredStyle = $this->styleManager->registerStyle($newCellStyle);
167 30
        $styleIndex = $registeredStyle->getId() + 1; // 1-based
168
169 30
        $numTimesValueRepeated = ($nextCellIndex - $currentCellIndex);
170
171 30
        return $this->getCellXML($cell, $styleIndex, $numTimesValueRepeated);
172
    }
173
174
    /**
175
     * Returns the cell XML content, given its value.
176
     *
177
     * @param Cell $cell The cell to be written
178
     * @param int $styleIndex Index of the used style
179
     * @param int $numTimesValueRepeated Number of times the value is consecutively repeated
180
     * @throws InvalidArgumentException If a cell value's type is not supported
181
     * @return string The cell XML content
182
     */
183 30
    private function getCellXML(Cell $cell, $styleIndex, $numTimesValueRepeated)
184
    {
185 30
        $data = '<table:table-cell table:style-name="ce' . $styleIndex . '"';
186
187 30
        if ($numTimesValueRepeated !== 1) {
188 4
            $data .= ' table:number-columns-repeated="' . $numTimesValueRepeated . '"';
189
        }
190
191 30
        if ($cell->isString()) {
192 26
            $data .= ' office:value-type="string" calcext:value-type="string">';
193
194 26
            $cellValueLines = explode("\n", $cell->getValue());
195 26
            foreach ($cellValueLines as $cellValueLine) {
196 26
                $data .= '<text:p>' . $this->stringsEscaper->escape($cellValueLine) . '</text:p>';
197
            }
198
199 26
            $data .= '</table:table-cell>';
200 6
        } elseif ($cell->isBoolean()) {
201 2
            $data .= ' office:value-type="boolean" calcext:value-type="boolean" office:boolean-value="' . $cell->getValue() . '">';
202 2
            $data .= '<text:p>' . $cell->getValue() . '</text:p>';
203 2
            $data .= '</table:table-cell>';
204 5
        } elseif ($cell->isNumeric()) {
205 2
            $data .= ' office:value-type="float" calcext:value-type="float" office:value="' . $cell->getValue() . '">';
206 2
            $data .= '<text:p>' . $cell->getValue() . '</text:p>';
207 2
            $data .= '</table:table-cell>';
208 4
        } elseif ($cell->isEmpty()) {
209 2
            $data .= '/>';
210
        } else {
211 2
            throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cell->getValue()));
212
        }
213
214 29
        return $data;
215
    }
216
217
    /**
218
     * Closes the worksheet
219
     *
220
     * @param Worksheet $worksheet
221
     * @return void
222
     */
223 33
    public function close(Worksheet $worksheet)
224
    {
225 33
        $worksheetFilePointer = $worksheet->getFilePointer();
226
227 33
        if (!is_resource($worksheetFilePointer)) {
228
            return;
229
        }
230
231 33
        fclose($worksheetFilePointer);
232 33
    }
233
}
234