Passed
Pull Request — develop_3.0 (#485)
by Adrien
02:50
created

WorkbookManagerAbstract::cleanupTempFolder()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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