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

WorkbookManagerAbstract::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 10
cts 10
cp 1
rs 9.6333
c 0
b 0
f 0
cc 1
nc 1
nop 8
crap 1

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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