Completed
Push — develop_3.0 ( b7e467...4ec3a2 )
by Adrien
02:33
created

WorksheetManager::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 9.6666
c 0
b 0
f 0
cc 1
eloc 7
nc 1
nop 3
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\StringHelper;
8
use Box\Spout\Writer\Common\Creator\EntityFactory;
9
use Box\Spout\Writer\Common\Entity\Cell;
10
use Box\Spout\Writer\Common\Entity\Worksheet;
11
use Box\Spout\Writer\Common\Manager\WorksheetManagerInterface;
12
use Box\Spout\Writer\Common\Entity\Style\Style;
13
use Box\Spout\Writer\ODS\Manager\Style\StyleManager;
14
15
/**
16
 * Class WorksheetManager
17
 * ODS worksheet manager, providing the interfaces to work with ODS worksheets.
18
 *
19
 * @package Box\Spout\Writer\ODS\Manager
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 EntityFactory Factory to create entities */
30
    private $entityFactory;
31
32
    /**
33
     * WorksheetManager constructor.
34
     *
35
     * @param \Box\Spout\Common\Helper\Escaper\ODS $stringsEscaper
36
     * @param StringHelper $stringHelper
37
     * @param EntityFactory $entityFactory
38
     */
39 43
    public function __construct(
40
        \Box\Spout\Common\Helper\Escaper\ODS $stringsEscaper,
41
        StringHelper $stringHelper,
42
        EntityFactory $entityFactory)
43
    {
44 43
        $this->stringsEscaper = $stringsEscaper;
45 43
        $this->stringHelper = $stringHelper;
46 43
        $this->entityFactory = $entityFactory;
47 43
    }
48
49
    /**
50
     * Prepares the worksheet to accept data
51
     *
52
     * @param Worksheet $worksheet The worksheet to start
53
     * @return void
54
     * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
55
     */
56 43
    public function startSheet(Worksheet $worksheet)
57
    {
58 43
        $sheetFilePointer = fopen($worksheet->getFilePath(), 'w');
59 43
        $this->throwIfSheetFilePointerIsNotAvailable($sheetFilePointer);
60
61 43
        $worksheet->setFilePointer($sheetFilePointer);
62 43
    }
63
64
    /**
65
     * Checks if the sheet has been sucessfully created. Throws an exception if not.
66
     *
67
     * @param bool|resource $sheetFilePointer Pointer to the sheet data file or FALSE if unable to open the file
68
     * @return void
69
     * @throws IOException If the sheet data file cannot be opened for writing
70
     */
71 43
    private function throwIfSheetFilePointerIsNotAvailable($sheetFilePointer)
72
    {
73 43
        if (!$sheetFilePointer) {
74
            throw new IOException('Unable to open sheet for writing.');
75
        }
76 43
    }
77
78
    /**
79
     * Returns the table XML root node as string.
80
     *
81
     * @param Worksheet $worksheet
82
     * @return string <table> node as string
83
     */
84 34
    public function getTableElementStartAsString(Worksheet $worksheet)
85
    {
86 34
        $externalSheet = $worksheet->getExternalSheet();
87 34
        $escapedSheetName = $this->stringsEscaper->escape($externalSheet->getName());
88 34
        $tableStyleName = 'ta' . ($externalSheet->getIndex() + 1);
89
90 34
        $tableElement  = '<table:table table:style-name="' . $tableStyleName . '" table:name="' . $escapedSheetName . '">';
91 34
        $tableElement .= '<table:table-column table:default-cell-style-name="ce1" table:style-name="co1" table:number-columns-repeated="' . $worksheet->getMaxNumColumns() . '"/>';
92
93 34
        return $tableElement;
94
    }
95
96
    /**
97
     * Adds data to the given worksheet.
98
     *
99
     * @param Worksheet $worksheet The worksheet to add the row to
100
     * @param array $dataRow Array containing data to be written. Cannot be empty.
101
     *          Example $dataRow = ['data1', 1234, null, '', 'data5'];
102
     * @param Style $rowStyle Style to be applied to the row. NULL means use default style.
103
     * @return void
104
     * @throws IOException If the data cannot be written
105
     * @throws InvalidArgumentException If a cell value's type is not supported
106
     */
107 31
    public function addRow(Worksheet $worksheet, $dataRow, $rowStyle)
108
    {
109
        // $dataRow can be an associative array. We need to transform
110
        // it into a regular array, as we'll use the numeric indexes.
111 31
        $dataRowWithNumericIndexes = array_values($dataRow);
112
113 31
        $styleIndex = ($rowStyle->getId() + 1); // 1-based
114 31
        $cellsCount = count($dataRow);
115
116 31
        $data = '<table:table-row table:style-name="ro1">';
117
118 31
        $currentCellIndex = 0;
119 31
        $nextCellIndex = 1;
120
121 31
        for ($i = 0; $i < $cellsCount; $i++) {
122 31
            $currentCellValue = $dataRowWithNumericIndexes[$currentCellIndex];
123
124
            // Using isset here because it is way faster than array_key_exists...
125 31
            if (!isset($dataRowWithNumericIndexes[$nextCellIndex]) ||
126 31
                $currentCellValue !== $dataRowWithNumericIndexes[$nextCellIndex]) {
127
128 31
                $numTimesValueRepeated = ($nextCellIndex - $currentCellIndex);
129 31
                $data .= $this->getCellXML($currentCellValue, $styleIndex, $numTimesValueRepeated);
130
131 30
                $currentCellIndex = $nextCellIndex;
132
            }
133
134 30
            $nextCellIndex++;
135
        }
136
137 30
        $data .= '</table:table-row>';
138
139 30
        $wasWriteSuccessful = fwrite($worksheet->getFilePointer(), $data);
140 30
        if ($wasWriteSuccessful === false) {
141
            throw new IOException("Unable to write data in {$worksheet->getFilePath()}");
142
        }
143
144
        // only update the count if the write worked
145 30
        $lastWrittenRowIndex = $worksheet->getLastWrittenRowIndex();
146 30
        $worksheet->setLastWrittenRowIndex($lastWrittenRowIndex + 1);
147 30
    }
148
149
    /**
150
     * Returns the cell XML content, given its value.
151
     *
152
     * @param mixed $cellValue The value to be written
153
     * @param int $styleIndex Index of the used style
154
     * @param int $numTimesValueRepeated Number of times the value is consecutively repeated
155
     * @return string The cell XML content
156
     * @throws \Box\Spout\Common\Exception\InvalidArgumentException If a cell value's type is not supported
157
     */
158 31
    private function getCellXML($cellValue, $styleIndex, $numTimesValueRepeated)
159
    {
160 31
        $data = '<table:table-cell table:style-name="ce' . $styleIndex . '"';
161
162 31
        if ($numTimesValueRepeated !== 1) {
163 4
            $data .= ' table:number-columns-repeated="' . $numTimesValueRepeated . '"';
164
        }
165
166
        /** @TODO Remove code duplication with XLSX writer: https://github.com/box/spout/pull/383#discussion_r113292746 */
167 31
        if ($cellValue instanceof Cell) {
168 2
            $cell = $cellValue;
169
        } else {
170 29
            $cell = $this->entityFactory->createCell($cellValue);
171
        }
172
173 31
        if ($cell->isString()) {
174 27
            $data .= ' office:value-type="string" calcext:value-type="string">';
175
176 27
            $cellValueLines = explode("\n", $cell->getValue());
177 27
            foreach ($cellValueLines as $cellValueLine) {
178 27
                $data .= '<text:p>' . $this->stringsEscaper->escape($cellValueLine) . '</text:p>';
179
            }
180
181 27
            $data .= '</table:table-cell>';
182 7
        } else if ($cell->isBoolean()) {
183 3
            $data .= ' office:value-type="boolean" calcext:value-type="boolean" office:boolean-value="' . $cell->getValue() . '">';
184 3
            $data .= '<text:p>' . $cell->getValue() . '</text:p>';
185 3
            $data .= '</table:table-cell>';
186 6
        } else if ($cell->isNumeric()) {
187 3
            $data .= ' office:value-type="float" calcext:value-type="float" office:value="' . $cell->getValue() . '">';
188 3
            $data .= '<text:p>' . $cell->getValue() . '</text:p>';
189 3
            $data .= '</table:table-cell>';
190 4
        } else if ($cell->isEmpty()) {
191 2
            $data .= '/>';
192
        } else {
193 2
            throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cell->getValue()));
194
        }
195
196 30
        return $data;
197
    }
198
199
    /**
200
     * Closes the worksheet
201
     *
202
     * @param Worksheet $worksheet
203
     * @return void
204
     */
205 34
    public function close(Worksheet $worksheet)
206
    {
207 34
        $worksheetFilePointer = $worksheet->getFilePointer();
208
209 34
        if (!is_resource($worksheetFilePointer)) {
210
            return;
211
        }
212
213 34
        fclose($worksheetFilePointer);
214 34
    }
215
}
216