Completed
Pull Request — develop_3.0 (#458)
by Adrien
01:54
created

WorkbookManagerAbstract::setCurrentSheet()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

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