Failed Conditions
Pull Request — develop_3.0 (#434)
by Hura
03:05
created

WorkbookManagerAbstract::getCurrentWorksheet()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

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 2
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 84
    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 84
        $this->workbook = $workbook;
68 84
        $this->optionManager = $optionsManager;
69 84
        $this->worksheetManager = $worksheetManager;
70 84
        $this->styleManager = $styleManager;
71 84
        $this->fileSystemHelper = $fileSystemHelper;
72 84
        $this->entityFactory = $entityFactory;
73 84
        $this->managerFactory = $managerFactory;
74 84
    }
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 67
    public function getWorkbook()
91
    {
92 67
        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 84
    public function addNewSheetAndMakeItCurrent()
103
    {
104 84
        $worksheet = $this->addNewSheet();
105 84
        $this->setCurrentWorksheet($worksheet);
106
107 84
        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 84
    private function addNewSheet()
117
    {
118 84
        $worksheets = $this->getWorksheets();
119
120 84
        $newSheetIndex = count($worksheets);
121 84
        $sheetManager = $this->managerFactory->createSheetManager();
122 84
        $sheet = $this->entityFactory->createSheet($newSheetIndex, $this->workbook->getInternalId(), $sheetManager);
123
124 84
        $worksheetFilePath = $this->getWorksheetFilePath($sheet);
125 84
        $worksheet = $this->entityFactory->createWorksheet($worksheetFilePath, $sheet);
126
127 84
        $this->worksheetManager->startSheet($worksheet);
128
129 84
        $worksheets[] = $worksheet;
130 84
        $this->workbook->setWorksheets($worksheets);
131
132 84
        return $worksheet;
133
    }
134
135
    /**
136
     * @return Worksheet[] All the workbook's sheets
137
     */
138 84
    public function getWorksheets()
139
    {
140 84
        return $this->workbook->getWorksheets();
141
    }
142
143
    /**
144
     * Returns the current sheet
145
     *
146
     * @return Worksheet The current sheet
147
     */
148 67
    public function getCurrentWorksheet()
149
    {
150 67
        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 84
    private function setCurrentWorksheet($worksheet)
176
    {
177 84
        $this->currentWorksheet = $worksheet;
178 84
    }
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 added
206
     * @return void
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 61
    public function addRowToCurrentWorksheet(Row $row)
212
    {
213 61
        $currentWorksheet = $this->getCurrentWorksheet();
214 61
        $hasReachedMaxRows = $this->hasCurrentWorksheetReachedMaxRows();
215
216
        // if we reached the maximum number of rows for the current sheet...
217 61
        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 61
            $this->addRowToWorksheet($currentWorksheet, $row);
228
        }
229 58
    }
230
231
    /**
232
     * @return bool Whether the current worksheet has reached the maximum number of rows per sheet.
233
     */
234 61
    private function hasCurrentWorksheetReachedMaxRows()
235
    {
236 61
        $currentWorksheet = $this->getCurrentWorksheet();
237
238 61
        return ($currentWorksheet->getLastWrittenRowIndex() >= $this->getMaxRowsPerWorksheet());
239
    }
240
241
    /**
242
     * Adds data with the given style 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
     * @return void
247
     * @throws WriterException If unable to write data
248
     * @return void
249
     */
250 61
    private function addRowToWorksheet(Worksheet $worksheet, Row $row)
251
    {
252 61
        $this->worksheetManager->addRow($worksheet, $row);
253
254
        // update max num columns for the worksheet
255 58
        $currentMaxNumColumns = $worksheet->getMaxNumColumns();
256 58
        $cellsCount = count($row->getCells());
257 58
        $worksheet->setMaxNumColumns(max($currentMaxNumColumns, $cellsCount));
258 58
    }
259
260
    /**
261
     * Closes the workbook and all its associated sheets.
262
     * All the necessary files are written to disk and zipped together to create the final file.
263
     * All the temporary files are then deleted.
264
     *
265
     * @param resource $finalFilePointer Pointer to the spreadsheet that will be created
266
     * @return void
267
     */
268 69
    public function close($finalFilePointer)
269
    {
270 69
        $this->closeAllWorksheets();
271 69
        $this->closeRemainingObjects();
272 69
        $this->writeAllFilesToDiskAndZipThem($finalFilePointer);
273 69
        $this->cleanupTempFolder();
274 69
    }
275
276
    /**
277
     * Closes custom objects that are still opened
278
     *
279
     * @return void
280
     */
281 34
    protected function closeRemainingObjects()
282
    {
283
        // do nothing by default
284 34
    }
285
286
    /**
287
     * Writes all the necessary files to disk and zip them together to create the final file.
288
     *
289
     * @param resource $finalFilePointer Pointer to the spreadsheet that will be created
290
     * @return void
291
     */
292
    abstract protected function writeAllFilesToDiskAndZipThem($finalFilePointer);
293
294
    /**
295
     * Closes all workbook's associated sheets.
296
     *
297
     * @return void
298
     */
299 69
    private function closeAllWorksheets()
300
    {
301 69
        $worksheets = $this->getWorksheets();
302
303 69
        foreach ($worksheets as $worksheet) {
304 69
            $this->worksheetManager->close($worksheet);
305
        }
306 69
    }
307
308
    /**
309
     * Deletes the root folder created in the temp folder and all its contents.
310
     *
311
     * @return void
312
     */
313 69
    protected function cleanupTempFolder()
314
    {
315 69
        $rootFolder = $this->fileSystemHelper->getRootFolder();
316 69
        $this->fileSystemHelper->deleteFolderRecursively($rootFolder);
317 69
    }
318
}
319