Failed Conditions
Pull Request — develop_3.0 (#594)
by
unknown
04:29
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
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 67
    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 67
        $this->workbook = $workbook;
74 67
        $this->optionsManager = $optionsManager;
75 67
        $this->worksheetManager = $worksheetManager;
76 67
        $this->styleManager = $styleManager;
77 67
        $this->styleMerger = $styleMerger;
78 67
        $this->fileSystemHelper = $fileSystemHelper;
79 67
        $this->entityFactory = $entityFactory;
80 67
        $this->managerFactory = $managerFactory;
81 67
    }
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 61
    public function getWorkbook()
98
    {
99 61
        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
     * @throws IOException If unable to open the sheet for writing
107
     * @return Worksheet The created sheet
108
     */
109 67
    public function addNewSheetAndMakeItCurrent()
110
    {
111 67
        $worksheet = $this->addNewSheet();
112 67
        $this->setCurrentWorksheet($worksheet);
113
114 67
        return $worksheet;
115
    }
116
117
    /**
118
     * Creates a new sheet in the workbook. The current sheet remains unchanged.
119
     *
120
     * @throws \Box\Spout\Common\Exception\IOException If unable to open the sheet for writing
121
     * @return Worksheet The created sheet
122
     */
123 67
    private function addNewSheet()
124
    {
125 67
        $worksheets = $this->getWorksheets();
126
127 67
        $newSheetIndex = count($worksheets);
128 67
        $sheetManager = $this->managerFactory->createSheetManager();
129 67
        $sheet = $this->entityFactory->createSheet($newSheetIndex, $this->workbook->getInternalId(), $sheetManager);
130
131 67
        $worksheetFilePath = $this->getWorksheetFilePath($sheet);
132 67
        $worksheet = $this->entityFactory->createWorksheet($worksheetFilePath, $sheet);
133
134 67
        $worksheets[] = $worksheet;
135 67
        $this->workbook->setWorksheets($worksheets);
136
137 67
        return $worksheet;
138
    }
139
140
    /**
141
     * @return Worksheet[] All the workbook's sheets
142
     */
143 67
    public function getWorksheets()
144
    {
145 67
        return $this->workbook->getWorksheets();
146
    }
147
148
    /**
149
     * Returns the current sheet
150
     *
151
     * @return Worksheet The current sheet
152
     */
153 61
    public function getCurrentWorksheet()
154
    {
155 61
        return $this->currentWorksheet;
156
    }
157
158
    /**
159
     * starts the current sheet and opens the file pointer
160
     *
161
     * @throws IOException
162
     */
163 55
    public function startCurrentSheet()
164
    {
165 55
        $this->worksheetManager->startSheet($this->getCurrentWorksheet());
166 55
    }
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 67
    private function setCurrentWorksheet($worksheet)
191
    {
192 67
        $this->currentWorksheet = $worksheet;
193 67
    }
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
     * @throws IOException If trying to create a new sheet and unable to open the sheet for writing
222
     * @throws WriterException If unable to write data
223
     * @return void
224
     */
225 55
    public function addRowToCurrentWorksheet(Row $row)
226
    {
227 55
        $currentWorksheet = $this->getCurrentWorksheet();
228 55
        $hasReachedMaxRows = $this->hasCurrentWorksheetReachedMaxRows();
229
230
        // if we reached the maximum number of rows for the current sheet...
231 55
        if ($hasReachedMaxRows) {
232
            // ... continue writing in a new sheet if option set
233 2
            if ($this->optionsManager->getOption(Options::SHOULD_CREATE_NEW_SHEETS_AUTOMATICALLY)) {
234
                $currentWorksheet = $this->addNewSheetAndMakeItCurrent();
235
236
                $this->addRowToWorksheet($currentWorksheet, $row);
237 2
            } else {
238
                // otherwise, do nothing as the data won't be written anyways
239
            }
240
        } else {
241 55
            $this->addRowToWorksheet($currentWorksheet, $row);
242
        }
243 53
    }
244
245
    /**
246
     * @return bool Whether the current worksheet has reached the maximum number of rows per sheet.
247
     */
248 55
    private function hasCurrentWorksheetReachedMaxRows()
249
    {
250 55
        $currentWorksheet = $this->getCurrentWorksheet();
251
252 55
        return ($currentWorksheet->getLastWrittenRowIndex() >= $this->getMaxRowsPerWorksheet());
253
    }
254
255
    /**
256
     * Adds a row to the given sheet.
257
     *
258
     * @param Worksheet $worksheet Worksheet to write the row to
259
     * @param Row $row The row to be added
260
     * @throws WriterException If unable to write data
261
     * @return void
262
     */
263 55
    private function addRowToWorksheet(Worksheet $worksheet, Row $row)
264
    {
265 55
        $this->applyDefaultRowStyle($row);
266 55
        $this->worksheetManager->addRow($worksheet, $row);
267
268
        // update max num columns for the worksheet
269 53
        $currentMaxNumColumns = $worksheet->getMaxNumColumns();
270 53
        $cellsCount = $row->getNumCells();
271 53
        $worksheet->setMaxNumColumns(max($currentMaxNumColumns, $cellsCount));
272 53
    }
273
274
    /**
275
     * @param Row $row
276
     */
277 55
    private function applyDefaultRowStyle(Row $row)
278
    {
279 55
        $defaultRowStyle = $this->optionsManager->getOption(Options::DEFAULT_ROW_STYLE);
280
281 55
        if ($defaultRowStyle !== null) {
282 55
            $mergedStyle = $this->styleMerger->merge($row->getStyle(), $defaultRowStyle);
283 55
            $row->setStyle($mergedStyle);
284
        }
285 55
    }
286
287
    /**
288
     * Closes the workbook and all its associated sheets.
289
     * All the necessary files are written to disk and zipped together to create the final file.
290
     * All the temporary files are then deleted.
291
     *
292
     * @param resource $finalFilePointer Pointer to the spreadsheet that will be created
293
     * @return void
294
     */
295 60
    public function close($finalFilePointer)
296
    {
297 60
        $this->closeAllWorksheets();
298 60
        $this->closeRemainingObjects();
299 60
        $this->writeAllFilesToDiskAndZipThem($finalFilePointer);
300 60
        $this->cleanupTempFolder();
301 60
    }
302
303
    /**
304
     * Closes custom objects that are still opened
305
     *
306
     * @return void
307
     */
308 30
    protected function closeRemainingObjects()
309
    {
310
        // do nothing by default
311 30
    }
312
313
    /**
314
     * Writes all the necessary files to disk and zip them together to create the final file.
315
     *
316
     * @param resource $finalFilePointer Pointer to the spreadsheet that will be created
317
     * @return void
318
     */
319
    abstract protected function writeAllFilesToDiskAndZipThem($finalFilePointer);
320
321
    /**
322
     * Closes all workbook's associated sheets.
323
     *
324
     * @return void
325
     */
326 60
    private function closeAllWorksheets()
327
    {
328 60
        $worksheets = $this->getWorksheets();
329
330 60
        foreach ($worksheets as $worksheet) {
331 60
            $this->worksheetManager->close($worksheet);
332
        }
333 60
    }
334
335
    /**
336
     * Deletes the root folder created in the temp folder and all its contents.
337
     *
338
     * @return void
339
     */
340 60
    protected function cleanupTempFolder()
341
    {
342 60
        $rootFolder = $this->fileSystemHelper->getRootFolder();
343 60
        $this->fileSystemHelper->deleteFolderRecursively($rootFolder);
344 60
    }
345
}
346