Passed
Pull Request — develop_3.0 (#485)
by Adrien
03:18
created

WorkbookManagerAbstract::closeRemainingObjects()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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