Test Setup Failed
Pull Request — develop_3.0 (#434)
by Hura
04:56
created

WorksheetManager::throwIfSheetFilePointerIsNotAvailable()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 4
cp 0.75
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 1
crap 2.0625
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\StringHelper;
8
use Box\Spout\Writer\Common\Creator\EntityFactory;
9
use Box\Spout\Writer\Common\Entity\Cell;
10
use Box\Spout\Writer\Common\Entity\Style\Style;
11
use Box\Spout\Writer\Common\Entity\Row;
12
use Box\Spout\Writer\Common\Entity\Worksheet;
13
use Box\Spout\Writer\Common\Manager\WorksheetManagerInterface;
14
use Box\Spout\Writer\ODS\Manager\Style\StyleManager;
15
16
/**
17
 * Class WorksheetManager
18
 * ODS worksheet manager, providing the interfaces to work with ODS worksheets.
19
 */
20
class WorksheetManager implements WorksheetManagerInterface
21
{
22
    /** @var \Box\Spout\Common\Helper\Escaper\ODS Strings escaper */
23
    private $stringsEscaper;
24
25
    /** @var StringHelper String helper */
26
    private $stringHelper;
27
28
    /** @var EntityFactory Factory to create entities */
29
    private $entityFactory;
30
31
    /** @var StyleManager Manages styles */
32
    private $styleManager;
33
34
    /**
35
     * WorksheetManager constructor.
36 43
     *
37
     * @param \Box\Spout\Common\Helper\Escaper\ODS $stringsEscaper
38
     * @param StyleManager $styleManager
39
     * @param \Box\Spout\Common\Escaper\ODS $stringsEscaper
40
     * @param StringHelper $stringHelper
41 43
     * @param EntityFactory $entityFactory
42 43
     */
43 43
    public function __construct(
44 43
        StyleManager $styleManager,
45
        \Box\Spout\Common\Escaper\ODS $stringsEscaper,
46
        StringHelper $stringHelper)
47
    {
48
        \Box\Spout\Common\Helper\Escaper\ODS $stringsEscaper,
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_VARIABLE
Loading history...
49
        StringHelper $stringHelper,
50
        EntityFactory $entityFactory
51
    ) {
52
        $this->stringsEscaper = $stringsEscaper;
53 43
        $this->stringHelper = $stringHelper;
54
        $this->styleManager = $styleManager;
55 43
        $this->entityFactory = $entityFactory;
56 43
    }
57
58 43
    /**
59 43
     * Prepares the worksheet to accept data
60
     *
61
     * @param Worksheet $worksheet The worksheet to start
62
     * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
63
     * @return void
64
     */
65
    public function startSheet(Worksheet $worksheet)
66
    {
67
        $sheetFilePointer = fopen($worksheet->getFilePath(), 'w');
68 43
        $this->throwIfSheetFilePointerIsNotAvailable($sheetFilePointer);
69
70 43
        $worksheet->setFilePointer($sheetFilePointer);
71
    }
72
73 43
    /**
74
     * Checks if the sheet has been sucessfully created. Throws an exception if not.
75
     *
76
     * @param bool|resource $sheetFilePointer Pointer to the sheet data file or FALSE if unable to open the file
77
     * @throws IOException If the sheet data file cannot be opened for writing
78
     * @return void
79
     */
80
    private function throwIfSheetFilePointerIsNotAvailable($sheetFilePointer)
81 34
    {
82
        if (!$sheetFilePointer) {
83 34
            throw new IOException('Unable to open sheet for writing.');
84 34
        }
85 34
    }
86
87 34
    /**
88 34
     * Returns the table XML root node as string.
89
     *
90 34
     * @param Worksheet $worksheet
91
     * @return string <table> node as string
92
     */
93
    public function getTableElementStartAsString(Worksheet $worksheet)
94
    {
95
        $externalSheet = $worksheet->getExternalSheet();
96
        $escapedSheetName = $this->stringsEscaper->escape($externalSheet->getName());
97
        $tableStyleName = 'ta' . ($externalSheet->getIndex() + 1);
98
99
        $tableElement  = '<table:table table:style-name="' . $tableStyleName . '" table:name="' . $escapedSheetName . '">';
100
        $tableElement .= '<table:table-column table:default-cell-style-name="ce1" table:style-name="co1" table:number-columns-repeated="' . $worksheet->getMaxNumColumns() . '"/>';
101
102
        return $tableElement;
103
    }
104 31
105
    /**
106
     * Adds a row to the worksheet.
107
     *
108 31
     * @param Worksheet $worksheet The worksheet to add the row to
109
     * @param Row $row The row to be added
110 31
     * @return void
111 31
     *
112
     * @throws IOException If the data cannot be written
113 31
     * @throws InvalidArgumentException If a cell value's type is not supported
114
     * @return void
115 31
     */
116 31
    public function addRow(Worksheet $worksheet, Row $row)
117
    {
118 31
119 31
        $cells = $row->getCells();
120
        $cellsCount = count($cells);
121
122 31
        $data = '<table:table-row table:style-name="ro1">';
123 31
124 31
        $currentCellIndex = 0;
125 31
        $nextCellIndex = 1;
126
127 30
        for ($i = 0; $i < $cellsCount; $i++) {
128
129
            /** @var Cell $cell */
130 30
            $cell = $cells[$currentCellIndex];
131
            /** @var Cell|null $nextCell */
132
            $nextCell = isset($cells[$nextCellIndex]) ? $cells[$nextCellIndex] : null;
133 30
134
            // @TODO refactoring: move this to its own method
135 30
            if (null === $nextCell || $cell->getValue() !== $nextCell->getValue()) {
136 30
137
                // Apply styles - the row style is merged at this point
138
                $cell->applyStyle($row->getStyle());
139
                $this->styleManager->applyExtraStylesIfNeeded($cell);
140
                $registeredStyle = $this->styleManager->registerStyle($cell->getStyle());
141 30
                $styleIndex = $registeredStyle->getId() + 1; // 1-based
142 30
143 30
                $numTimesValueRepeated = ($nextCellIndex - $currentCellIndex);
144
                $data .= $this->getCellXML($cell, $styleIndex, $numTimesValueRepeated);
145
                $currentCellIndex = $nextCellIndex;
146
            }
147
148
            $nextCellIndex++;
149
        }
150
151
        $data .= '</table:table-row>';
152
153
        $wasWriteSuccessful = fwrite($worksheet->getFilePointer(), $data);
154 31
        if ($wasWriteSuccessful === false) {
155
            throw new IOException("Unable to write data in {$worksheet->getFilePath()}");
156 31
        }
157
158 31
        // only update the count if the write worked
159 4
        $lastWrittenRowIndex = $worksheet->getLastWrittenRowIndex();
160
        $worksheet->setLastWrittenRowIndex($lastWrittenRowIndex + 1);
161
    }
162
163 31
    /**
164 2
     * Returns the cell XML content, given its value.
165
     *
166 29
     * @param Cell $cell The cell to be written
167
     * @param int $styleIndex Index of the used style
168
     * @param int $numTimesValueRepeated Number of times the value is consecutively repeated
169 31
     * @throws \Box\Spout\Common\Exception\InvalidArgumentException If a cell value's type is not supported
170 27
     * @return string The cell XML content
171
     */
172 27
    protected function getCellXML(Cell $cell, $styleIndex, $numTimesValueRepeated)
173 27
    {
174 27
        $data = '<table:table-cell table:style-name="ce' . $styleIndex . '"';
175
176
        if ($numTimesValueRepeated !== 1) {
177 27
            $data .= ' table:number-columns-repeated="' . $numTimesValueRepeated . '"';
178 7
        }
179 3
180 3
        if ($cell->isString()) {
181 3
            $data .= ' office:value-type="string" calcext:value-type="string">';
182 6
183 3
            $cellValueLines = explode("\n", $cell->getValue());
184 3
            foreach ($cellValueLines as $cellValueLine) {
185 3
                $data .= '<text:p>' . $this->stringsEscaper->escape($cellValueLine) . '</text:p>';
186 4
            }
187 2
188
            $data .= '</table:table-cell>';
189 2
        } elseif ($cell->isBoolean()) {
190
            $data .= ' office:value-type="boolean" calcext:value-type="boolean" office:boolean-value="' . $cell->getValue() . '">';
191
            $data .= '<text:p>' . $cell->getValue() . '</text:p>';
192 30
            $data .= '</table:table-cell>';
193
        } elseif ($cell->isNumeric()) {
194
            $data .= ' office:value-type="float" calcext:value-type="float" office:value="' . $cell->getValue() . '">';
195
            $data .= '<text:p>' . $cell->getValue() . '</text:p>';
196
            $data .= '</table:table-cell>';
197
        } elseif ($cell->isEmpty()) {
198
            $data .= '/>';
199
        } else {
200
            throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cell->getValue()));
201 34
        }
202
203 34
        return $data;
204
    }
205 34
206
    /**
207
     * Closes the worksheet
208
     *
209 34
     * @param Worksheet $worksheet
210 34
     * @return void
211
     */
212
    public function close(Worksheet $worksheet)
213
    {
214
        $worksheetFilePointer = $worksheet->getFilePointer();
215
216
        if (!is_resource($worksheetFilePointer)) {
217
            return;
218
        }
219
220
        fclose($worksheetFilePointer);
221
    }
222
}
223