Failed Conditions
Pull Request — master (#715)
by
unknown
03:04
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 88
    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 88
        $this->workbook = $workbook;
73 88
        $this->optionsManager = $optionsManager;
74 88
        $this->worksheetManager = $worksheetManager;
75 88
        $this->styleManager = $styleManager;
76 88
        $this->styleMerger = $styleMerger;
77 88
        $this->fileSystemHelper = $fileSystemHelper;
78 88
        $this->entityFactory = $entityFactory;
79 88
        $this->managerFactory = $managerFactory;
80 88
    }
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 82
    public function getWorkbook()
97
    {
98 82
        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 88
    public function addNewSheetAndMakeItCurrent()
108
    {
109 88
        $worksheet = $this->addNewSheet();
110 88
        $this->setCurrentWorksheet($worksheet);
111
112 88
        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 88
    private function addNewSheet()
122
    {
123 88
        $worksheets = $this->getWorksheets();
124
125 88
        $newSheetIndex = \count($worksheets);
126 88
        $sheetManager = $this->managerFactory->createSheetManager();
127 88
        $sheet = $this->entityFactory->createSheet($newSheetIndex, $this->workbook->getInternalId(), $sheetManager);
128
129 88
        $worksheetFilePath = $this->getWorksheetFilePath($sheet);
130 88
        $worksheet = $this->entityFactory->createWorksheet($worksheetFilePath, $sheet);
131
132 88
        $this->worksheetManager->startSheet($worksheet);
133
134 88
        $worksheets[] = $worksheet;
135 88
        $this->workbook->setWorksheets($worksheets);
136
137 88
        return $worksheet;
138
    }
139
140
    /**
141
     * @return Worksheet[] All the workbook's sheets
142
     */
143 88
    public function getWorksheets()
144
    {
145 88
        return $this->workbook->getWorksheets();
146
    }
147
148
    /**
149
     * Returns the current sheet
150
     *
151
     * @return Worksheet The current sheet
152
     */
153 82
    public function getCurrentWorksheet()
154
    {
155 82
        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 88
    private function setCurrentWorksheet($worksheet)
191
    {
192 88
        $this->currentWorksheet = $worksheet;
193 88
    }
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 76
    public function addRowToCurrentWorksheet(Row $row)
227
    {
228 76
        $currentWorksheet = $this->getCurrentWorksheet();
229 76
        $hasReachedMaxRows = $this->hasCurrentWorksheetReachedMaxRows();
230
231
        // if we reached the maximum number of rows for the current sheet...
232 76
        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 76
            $this->addRowToWorksheet($currentWorksheet, $row);
243
        }
244 74
    }
245
246
    /**
247
     * @return bool Whether the current worksheet has reached the maximum number of rows per sheet.
248
     */
249 76
    private function hasCurrentWorksheetReachedMaxRows()
250
    {
251 76
        $currentWorksheet = $this->getCurrentWorksheet();
252
253 76
        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 76
    private function addRowToWorksheet(Worksheet $worksheet, Row $row)
267
    {
268 76
        $this->applyDefaultRowStyle($row);
269 76
        $this->worksheetManager->addRow($worksheet, $row);
270
271
        // update max num columns for the worksheet
272 74
        $currentMaxNumColumns = $worksheet->getMaxNumColumns();
273 74
        $cellsCount = $row->getNumCells();
274 74
        $worksheet->setMaxNumColumns(\max($currentMaxNumColumns, $cellsCount));
275 74
    }
276
277
    /**
278
     * @param Row $row
279
     */
280 76
    private function applyDefaultRowStyle(Row $row)
281
    {
282 76
        $defaultRowStyle = $this->optionsManager->getOption(Options::DEFAULT_ROW_STYLE);
283
284 76
        if ($defaultRowStyle !== null) {
285 76
            $mergedStyle = $this->styleMerger->merge($row->getStyle(), $defaultRowStyle);
286 76
            $row->setStyle($mergedStyle);
287
        }
288 76
    }
289
290
    /**
291
     * @param float $width
292
     */
293
    public function setDefaultColumnWidth(float $width)
294
    {
295
        $this->worksheetManager->setDefaultColumnWidth($width);
296
    }
297
298
    /**
299
     * @param float $height
300
     */
301
    public function setDefaultRowHeight(float $height)
302
    {
303
        $this->worksheetManager->setDefaultRowHeight($height);
304
    }
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 81
    public function close($finalFilePointer)
334
    {
335 81
        $this->closeAllWorksheets();
336 81
        $this->closeRemainingObjects();
337 81
        $this->writeAllFilesToDiskAndZipThem($finalFilePointer);
338 81
        $this->cleanupTempFolder();
339 81
    }
340
341
    /**
342
     * Closes custom objects that are still opened
343
     *
344
     * @return void
345
     */
346 39
    protected function closeRemainingObjects()
347
    {
348
        // do nothing by default
349 39
    }
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 81
    private function closeAllWorksheets()
365
    {
366 81
        $worksheets = $this->getWorksheets();
367
368 81
        foreach ($worksheets as $worksheet) {
369 81
            $this->worksheetManager->close($worksheet);
370
        }
371 81
    }
372
373
    /**
374
     * Deletes the root folder created in the temp folder and all its contents.
375
     *
376
     * @return void
377
     */
378 81
    protected function cleanupTempFolder()
379
    {
380 81
        $rootFolder = $this->fileSystemHelper->getRootFolder();
381 81
        $this->fileSystemHelper->deleteFolderRecursively($rootFolder);
382 81
    }
383
}
384