Completed
Pull Request — master (#715)
by
unknown
01:52
created

WorkbookManagerAbstract::setCurrentWorksheet()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Box\Spout\Writer\Common\Manager;
4
5
use Box\Spout\Common\Entity\Row;
6
use Box\Spout\Common\Exception\IOException;
7
use Box\Spout\Common\Manager\OptionsManagerInterface;
8
use Box\Spout\Writer\Common\Creator\InternalEntityFactory;
9
use Box\Spout\Writer\Common\Creator\ManagerFactoryInterface;
10
use Box\Spout\Writer\Common\Entity\Options;
11
use Box\Spout\Writer\Common\Entity\Sheet;
12
use Box\Spout\Writer\Common\Entity\Workbook;
13
use Box\Spout\Writer\Common\Entity\Worksheet;
14
use Box\Spout\Writer\Common\Helper\FileSystemWithRootFolderHelperInterface;
15
use Box\Spout\Writer\Common\Manager\Style\StyleManagerInterface;
16
use Box\Spout\Writer\Common\Manager\Style\StyleMerger;
17
use Box\Spout\Writer\Exception\SheetNotFoundException;
18
use Box\Spout\Writer\Exception\WriterException;
19
20
/**
21
 * Class WorkbookManagerAbstract
22
 * Abstract workbook manager, providing the generic interfaces to work with workbook.
23
 */
24
abstract class WorkbookManagerAbstract implements WorkbookManagerInterface
25
{
26
    /** @var Workbook The workbook to manage */
27
    protected $workbook;
28
29
    /** @var OptionsManagerInterface */
30
    protected $optionsManager;
31
32
    /** @var WorksheetManagerInterface */
33
    protected $worksheetManager;
34
35
    /** @var StyleManagerInterface Manages styles */
36
    protected $styleManager;
37
38
    /** @var StyleMerger Helper to merge styles */
39
    protected $styleMerger;
40
41
    /** @var FileSystemWithRootFolderHelperInterface Helper to perform file system operations */
42
    protected $fileSystemHelper;
43
44
    /** @var InternalEntityFactory Factory to create entities */
45
    protected $entityFactory;
46
47
    /** @var ManagerFactoryInterface $managerFactory Factory to create managers */
48
    protected $managerFactory;
49
50
    /** @var Worksheet The worksheet where data will be written to */
51
    protected $currentWorksheet;
52
53
    /**
54
     * @param Workbook $workbook
55
     * @param OptionsManagerInterface $optionsManager
56
     * @param WorksheetManagerInterface $worksheetManager
57
     * @param StyleManagerInterface $styleManager
58
     * @param StyleMerger $styleMerger
59
     * @param FileSystemWithRootFolderHelperInterface $fileSystemHelper
60
     * @param InternalEntityFactory $entityFactory
61
     * @param ManagerFactoryInterface $managerFactory
62
     */
63 91
    public function __construct(
64
        Workbook $workbook,
65
        OptionsManagerInterface $optionsManager,
66
        WorksheetManagerInterface $worksheetManager,
67
        StyleManagerInterface $styleManager,
68
        StyleMerger $styleMerger,
69
        FileSystemWithRootFolderHelperInterface $fileSystemHelper,
70
        InternalEntityFactory $entityFactory,
71
        ManagerFactoryInterface $managerFactory
72
    ) {
73 91
        $this->workbook = $workbook;
74 91
        $this->optionsManager = $optionsManager;
75 91
        $this->worksheetManager = $worksheetManager;
76 91
        $this->styleManager = $styleManager;
77 91
        $this->styleMerger = $styleMerger;
78 91
        $this->fileSystemHelper = $fileSystemHelper;
79 91
        $this->entityFactory = $entityFactory;
80 91
        $this->managerFactory = $managerFactory;
81 91
    }
82
83
    /**
84
     * @return int Maximum number of rows/columns a sheet can contain
85
     */
86
    abstract protected function getMaxRowsPerWorksheet();
87
88
    /**
89
     * @param Sheet $sheet
90
     * @return string The file path where the data for the given sheet will be stored
91
     */
92
    abstract protected function getWorksheetFilePath(Sheet $sheet);
93
94
    /**
95
     * @return Workbook
96
     */
97 85
    public function getWorkbook()
98
    {
99 85
        return $this->workbook;
100
    }
101
102
    /**
103
     * Creates a new sheet in the workbook and make it the current sheet.
104
     * The writing will resume where it stopped (i.e. data won't be truncated).
105
     *
106
     * @return Worksheet The created sheet
107
     */
108 91
    public function addNewSheetAndMakeItCurrent()
109
    {
110 91
        $worksheet = $this->addNewSheet();
111 91
        $this->setCurrentWorksheet($worksheet);
112
113 91
        return $worksheet;
114
    }
115
116
    /**
117
     * Creates a new sheet in the workbook. The current sheet remains unchanged.
118
     *
119
     * @return Worksheet The created sheet
120
     * @throws IOException
121
     */
122 91
    private function addNewSheet()
123
    {
124 91
        $worksheets = $this->getWorksheets();
125
126 91
        $newSheetIndex = \count($worksheets);
127 91
        $sheetManager = $this->managerFactory->createSheetManager();
128 91
        $sheet = $this->entityFactory->createSheet($newSheetIndex, $this->workbook->getInternalId(), $sheetManager);
129
130 91
        $worksheetFilePath = $this->getWorksheetFilePath($sheet);
131 91
        $worksheet = $this->entityFactory->createWorksheet($worksheetFilePath, $sheet);
132
133 91
        $this->worksheetManager->startSheet($worksheet);
134
135 91
        $worksheets[] = $worksheet;
136 91
        $this->workbook->setWorksheets($worksheets);
137
138 91
        return $worksheet;
139
    }
140
141
    /**
142
     * @return Worksheet[] All the workbook's sheets
143
     */
144 91
    public function getWorksheets()
145
    {
146 91
        return $this->workbook->getWorksheets();
147
    }
148
149
    /**
150
     * Returns the current sheet
151
     *
152
     * @return Worksheet The current sheet
153
     */
154 85
    public function getCurrentWorksheet()
155
    {
156 85
        return $this->currentWorksheet;
157
    }
158
159
    /**
160
     * Starts the current sheet and opens the file pointer
161
     *
162
     * @throws IOException
163
     */
164
    public function startCurrentSheet()
165
    {
166
        $this->worksheetManager->startSheet($this->getCurrentWorksheet());
167
    }
168
169
    /**
170
     * Sets the given sheet as the current one. New data will be written to this sheet.
171
     * The writing will resume where it stopped (i.e. data won't be truncated).
172
     *
173
     * @param Sheet $sheet The "external" sheet to set as current
174
     * @return void
175
     * @throws SheetNotFoundException If the given sheet does not exist in the workbook
176
     */
177 4
    public function setCurrentSheet(Sheet $sheet)
178
    {
179 4
        $worksheet = $this->getWorksheetFromExternalSheet($sheet);
180 4
        if ($worksheet !== null) {
181 4
            $this->currentWorksheet = $worksheet;
182
        } else {
183
            throw new SheetNotFoundException('The given sheet does not exist in the workbook.');
184
        }
185 4
    }
186
187
    /**
188
     * @param Worksheet $worksheet
189
     * @return void
190
     */
191 91
    private function setCurrentWorksheet($worksheet)
192
    {
193 91
        $this->currentWorksheet = $worksheet;
194 91
    }
195
196
    /**
197
     * Returns the worksheet associated to the given external sheet.
198
     *
199
     * @param Sheet $sheet
200
     * @return Worksheet|null The worksheet associated to the given external sheet or null if not found.
201
     */
202 4
    private function getWorksheetFromExternalSheet($sheet)
203
    {
204 4
        $worksheetFound = null;
205
206 4
        foreach ($this->getWorksheets() as $worksheet) {
207 4
            if ($worksheet->getExternalSheet() === $sheet) {
208 4
                $worksheetFound = $worksheet;
209 4
                break;
210
            }
211
        }
212
213 4
        return $worksheetFound;
214
    }
215
216
    /**
217
     * Adds a row to the current sheet.
218
     * If shouldCreateNewSheetsAutomatically option is set to true, it will handle pagination
219
     * with the creation of new worksheets if one worksheet has reached its maximum capicity.
220
     *
221
     * @param Row $row The row to be added
222
     *
223
     * @return void
224
     * @throws IOException If trying to create a new sheet and unable to open the sheet for writing
225
     * @throws \Box\Spout\Common\Exception\InvalidArgumentException
226
     */
227 79
    public function addRowToCurrentWorksheet(Row $row)
228
    {
229 79
        $currentWorksheet = $this->getCurrentWorksheet();
230 79
        $hasReachedMaxRows = $this->hasCurrentWorksheetReachedMaxRows();
231
232
        // if we reached the maximum number of rows for the current sheet...
233 79
        if ($hasReachedMaxRows) {
234
            // ... continue writing in a new sheet if option set
235 4
            if ($this->optionsManager->getOption(Options::SHOULD_CREATE_NEW_SHEETS_AUTOMATICALLY)) {
236 2
                $currentWorksheet = $this->addNewSheetAndMakeItCurrent();
237
238 2
                $this->addRowToWorksheet($currentWorksheet, $row);
239 4
            } else {
240
                // otherwise, do nothing as the data won't be written anyways
241
            }
242
        } else {
243 79
            $this->addRowToWorksheet($currentWorksheet, $row);
244
        }
245 77
    }
246
247
    /**
248
     * @return bool Whether the current worksheet has reached the maximum number of rows per sheet.
249
     */
250 79
    private function hasCurrentWorksheetReachedMaxRows()
251
    {
252 79
        $currentWorksheet = $this->getCurrentWorksheet();
253
254 79
        return ($currentWorksheet->getLastWrittenRowIndex() >= $this->getMaxRowsPerWorksheet());
255
    }
256
257
    /**
258
     * Adds a row to the given sheet.
259
     *
260
     * @param Worksheet $worksheet Worksheet to write the row to
261
     * @param Row $row The row to be added
262
     *
263
     * @return void
264
     * @throws IOException
265
     * @throws \Box\Spout\Common\Exception\InvalidArgumentException
266
     */
267 79
    private function addRowToWorksheet(Worksheet $worksheet, Row $row)
268
    {
269 79
        $this->applyDefaultRowStyle($row);
270 79
        $this->worksheetManager->addRow($worksheet, $row);
271
272
        // update max num columns for the worksheet
273 77
        $currentMaxNumColumns = $worksheet->getMaxNumColumns();
274 77
        $cellsCount = $row->getNumCells();
275 77
        $worksheet->setMaxNumColumns(\max($currentMaxNumColumns, $cellsCount));
276 77
    }
277
278
    /**
279
     * @param Row $row
280
     */
281 79
    private function applyDefaultRowStyle(Row $row)
282
    {
283 79
        $defaultRowStyle = $this->optionsManager->getOption(Options::DEFAULT_ROW_STYLE);
284
285 79
        if ($defaultRowStyle !== null) {
286 79
            $mergedStyle = $this->styleMerger->merge($row->getStyle(), $defaultRowStyle);
287 79
            $row->setStyle($mergedStyle);
288
        }
289 79
    }
290
291
    /**
292
     * @param float $width
293
     */
294 3
    public function setDefaultColumnWidth(float $width)
295
    {
296 3
        $this->worksheetManager->setDefaultColumnWidth($width);
297 3
    }
298
299
    /**
300
     * @param float $height
301
     */
302 2
    public function setDefaultRowHeight(float $height)
303
    {
304 2
        $this->worksheetManager->setDefaultRowHeight($height);
305 2
    }
306
307
    /**
308
     * @param float $width
309
     * @param array $columns One or more columns with this width
310
     */
311 6
    public function setColumnWidth(float $width, ...$columns)
312
    {
313 6
        $this->worksheetManager->setColumnWidth($width, ...$columns);
314 6
    }
315
316
    /**
317
     * @param float $width The width to set
318
     * @param int $start First column index of the range
319
     * @param int $end Last column index of the range
320
     */
321 2
    public function setColumnWidthForRange(float $width, int $start, int $end)
322
    {
323 2
        $this->worksheetManager->setColumnWidthForRange($width, $start, $end);
324 2
    }
325
326
    /**
327
     * Closes the workbook and all its associated sheets.
328
     * All the necessary files are written to disk and zipped together to create the final file.
329
     * All the temporary files are then deleted.
330
     *
331
     * @param resource $finalFilePointer Pointer to the spreadsheet that will be created
332
     * @return void
333
     */
334 84
    public function close($finalFilePointer)
335
    {
336 84
        $this->closeAllWorksheets();
337 84
        $this->closeRemainingObjects();
338 84
        $this->writeAllFilesToDiskAndZipThem($finalFilePointer);
339 84
        $this->cleanupTempFolder();
340 84
    }
341
342
    /**
343
     * Closes custom objects that are still opened
344
     *
345
     * @return void
346
     */
347 40
    protected function closeRemainingObjects()
348
    {
349
        // do nothing by default
350 40
    }
351
352
    /**
353
     * Writes all the necessary files to disk and zip them together to create the final file.
354
     *
355
     * @param resource $finalFilePointer Pointer to the spreadsheet that will be created
356
     * @return void
357
     */
358
    abstract protected function writeAllFilesToDiskAndZipThem($finalFilePointer);
359
360
    /**
361
     * Closes all workbook's associated sheets.
362
     *
363
     * @return void
364
     */
365 84
    private function closeAllWorksheets()
366
    {
367 84
        $worksheets = $this->getWorksheets();
368
369 84
        foreach ($worksheets as $worksheet) {
370 84
            $this->worksheetManager->close($worksheet);
371
        }
372 84
    }
373
374
    /**
375
     * Deletes the root folder created in the temp folder and all its contents.
376
     *
377
     * @return void
378
     */
379 84
    protected function cleanupTempFolder()
380
    {
381 84
        $rootFolder = $this->fileSystemHelper->getRootFolder();
382 84
        $this->fileSystemHelper->deleteFolderRecursively($rootFolder);
383 84
    }
384
}
385