Test Setup Failed
Pull Request — develop_3.0 (#434)
by Hura
04:56
created

WorkbookManagerAbstract::addNewSheetAndMakeItCurrent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
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\Manager\Style\StyleManagerInterface;
11
use Box\Spout\Writer\Common\Entity\Row;
12
use Box\Spout\Writer\Common\Entity\Sheet;
13
use Box\Spout\Writer\Common\Entity\Style\Style;
14
use Box\Spout\Writer\Common\Entity\Workbook;
15
use Box\Spout\Writer\Common\Entity\Worksheet;
16
use Box\Spout\Writer\Common\Helper\FileSystemWithRootFolderHelperInterface;
17
use Box\Spout\Writer\Common\Manager\Style\StyleManagerInterface;
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Cannot use Box\Spout\Writer\Common\Manager\Style\StyleManagerInterface as StyleManagerInterface because the name is already in use
Loading history...
18
use Box\Spout\Writer\Exception\SheetNotFoundException;
19
use Box\Spout\Writer\Exception\WriterException;
20
use Box\Spout\Writer\Common\Creator\EntityFactory;
21
22
/**
23
 * Class WorkbookManagerAbstract
24
 * Abstract workbook manager, providing the generic interfaces to work with workbook.
25
 */
26
abstract class WorkbookManagerAbstract implements WorkbookManagerInterface
27
{
28
    /** @var Workbook The workbook to manage */
29
    protected $workbook;
30
31
    /** @var OptionsManagerInterface */
32
    protected $optionManager;
33
34
    /** @var WorksheetManagerInterface */
35
    protected $worksheetManager;
36
37
    /** @var StyleManagerInterface Manages styles */
38
    protected $styleManager;
39
40
    /** @var FileSystemWithRootFolderHelperInterface Helper to perform file system operations */
41
    protected $fileSystemHelper;
42
43
    /** @var EntityFactory Factory to create entities */
44
    protected $entityFactory;
45
46
    /** @var ManagerFactoryInterface $managerFactory Factory to create managers */
47
    protected $managerFactory;
48
49
    /** @var Worksheet The worksheet where data will be written to */
50
    protected $currentWorksheet;
51
52
    /**
53
     * @param Workbook $workbook
54
     * @param OptionsManagerInterface $optionsManager
55
     * @param WorksheetManagerInterface $worksheetManager
56
     * @param StyleManagerInterface $styleManager
57
     * @param FileSystemWithRootFolderHelperInterface $fileSystemHelper
58 89
     * @param EntityFactory $entityFactory
59
     * @param ManagerFactoryInterface $managerFactory
60
     */
61
    public function __construct(
62
        Workbook $workbook,
63
        OptionsManagerInterface $optionsManager,
64
        WorksheetManagerInterface $worksheetManager,
65
        StyleManagerInterface $styleManager,
66
        FileSystemWithRootFolderHelperInterface $fileSystemHelper,
67 89
        EntityFactory $entityFactory,
68 89
        ManagerFactoryInterface $managerFactory
69 89
    ) {
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
        $this->entityFactory = $entityFactory;
76
        $this->managerFactory = $managerFactory;
77
    }
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 70
    /**
91
     * @return Workbook
92 70
     */
93
    public function getWorkbook()
94
    {
95
        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 89
     * @throws IOException If unable to open the sheet for writing
103
     * @return Worksheet The created sheet
104 89
     */
105 89
    public function addNewSheetAndMakeItCurrent()
106
    {
107 89
        $worksheet = $this->addNewSheet();
108
        $this->setCurrentWorksheet($worksheet);
109
110
        return $worksheet;
111
    }
112
113
    /**
114
     * Creates a new sheet in the workbook. The current sheet remains unchanged.
115
     *
116 89
     * @throws \Box\Spout\Common\Exception\IOException If unable to open the sheet for writing
117
     * @return Worksheet The created sheet
118 89
     */
119
    private function addNewSheet()
120 89
    {
121 89
        $worksheets = $this->getWorksheets();
122 89
123
        $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
        $worksheet = $this->entityFactory->createWorksheet($worksheetFilePath, $sheet);
129 89
130 89
        $this->worksheetManager->startSheet($worksheet);
131
132 89
        $worksheets[] = $worksheet;
133
        $this->workbook->setWorksheets($worksheets);
134
135
        return $worksheet;
136
    }
137
138 89
    /**
139
     * @return Worksheet[] All the workbook's sheets
140 89
     */
141
    public function getWorksheets()
142
    {
143
        return $this->workbook->getWorksheets();
144
    }
145
146
    /**
147
     * Returns the current sheet
148 70
     *
149
     * @return Worksheet The current sheet
150 70
     */
151
    public function getCurrentWorksheet()
152
    {
153
        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 4
     * @throws SheetNotFoundException If the given sheet does not exist in the workbook
162
     * @return void
163 4
     */
164 4
    public function setCurrentSheet(Sheet $sheet)
165 4
    {
166
        $worksheet = $this->getWorksheetFromExternalSheet($sheet);
167
        if ($worksheet !== null) {
168
            $this->currentWorksheet = $worksheet;
169 4
        } else {
170
            throw new SheetNotFoundException('The given sheet does not exist in the workbook.');
171
        }
172
    }
173
174
    /**
175 89
     * @param Worksheet $worksheet
176
     * @return void
177 89
     */
178 89
    private function setCurrentWorksheet($worksheet)
179
    {
180
        $this->currentWorksheet = $worksheet;
181
    }
182
183
    /**
184
     * Returns the worksheet associated to the given external sheet.
185
     *
186 4
     * @param Sheet $sheet
187
     * @return Worksheet|null The worksheet associated to the given external sheet or null if not found.
188 4
     */
189
    private function getWorksheetFromExternalSheet($sheet)
190 4
    {
191 4
        $worksheetFound = null;
192 4
193 4
        foreach ($this->getWorksheets() as $worksheet) {
194
            if ($worksheet->getExternalSheet() === $sheet) {
195
                $worksheetFound = $worksheet;
196
                break;
197 4
            }
198
        }
199
200
        return $worksheetFound;
201
    }
202
203
    /**
204
     * Adds a row 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 Row $row The row to added
209
     * @return void
210
     * @throws IOException If trying to create a new sheet and unable to open the sheet for writing
211
     * @throws WriterException If unable to write data
212 64
     * @return void
213
     */
214 64
    public function addRowToCurrentWorksheet(Row $row)
215 64
    {
216
        $currentWorksheet = $this->getCurrentWorksheet();
217
        $hasReachedMaxRows = $this->hasCurrentWorksheetReachedMaxRows();
218 64
219
        // if we reached the maximum number of rows for the current sheet...
220 4
        if ($hasReachedMaxRows) {
221 2
            // ... continue writing in a new sheet if option set
222
            if ($this->optionManager->getOption(Options::SHOULD_CREATE_NEW_SHEETS_AUTOMATICALLY)) {
223 2
                $currentWorksheet = $this->addNewSheetAndMakeItCurrent();
224 4
225
                $this->addRowToWorksheet($currentWorksheet, $row);
226
            } else {
227
                // otherwise, do nothing as the data won't be written anyways
228 64
            }
229
        } else {
230 61
            $this->addRowToWorksheet($currentWorksheet, $row);
231
        }
232
    }
233
234
    /**
235 64
     * @return bool Whether the current worksheet has reached the maximum number of rows per sheet.
236
     */
237 64
    private function hasCurrentWorksheetReachedMaxRows()
238
    {
239 64
        $currentWorksheet = $this->getCurrentWorksheet();
240
241
        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 Row $row The row to be added
249
     * @return void
250
     * @throws WriterException If unable to write data
251
     * @return void
252 64
     */
253
    private function addRowToWorksheet(Worksheet $worksheet, Row $row)
254 64
    {
255 64
        $this->worksheetManager->addRow($worksheet, $row);
256 64
257
        // update max num columns for the worksheet
258
        $currentMaxNumColumns = $worksheet->getMaxNumColumns();
259 61
        $cellsCount = count($row->getCells());
260 61
        $worksheet->setMaxNumColumns(max($currentMaxNumColumns, $cellsCount));
261 61
    }
262 61
263
    /**
264
     * Closes the workbook and all its associated sheets.
265
     * All the necessary files are written to disk and zipped together to create the final file.
266
     * All the temporary files are then deleted.
267
     *
268
     * @param resource $finalFilePointer Pointer to the spreadsheet that will be created
269
     * @return void
270
     */
271
    public function close($finalFilePointer)
272 70
    {
273
        $this->closeAllWorksheets();
274 70
        $this->closeRemainingObjects();
275 70
        $this->writeAllFilesToDiskAndZipThem($finalFilePointer);
276 70
        $this->cleanupTempFolder();
277 70
    }
278 70
279
    /**
280
     * Closes custom objects that are still opened
281
     *
282
     * @return void
283
     */
284
    protected function closeRemainingObjects()
285 34
    {
286
        // do nothing by default
287
    }
288 34
289
    /**
290
     * Writes all the necessary files to disk and zip them together to create the final file.
291
     *
292
     * @param resource $finalFilePointer Pointer to the spreadsheet that will be created
293
     * @return void
294
     */
295
    abstract protected function writeAllFilesToDiskAndZipThem($finalFilePointer);
296
297
    /**
298
     * Closes all workbook's associated sheets.
299
     *
300
     * @return void
301
     */
302
    private function closeAllWorksheets()
303 70
    {
304
        $worksheets = $this->getWorksheets();
305 70
306
        foreach ($worksheets as $worksheet) {
307 70
            $this->worksheetManager->close($worksheet);
308 70
        }
309
    }
310 70
311
    /**
312
     * Deletes the root folder created in the temp folder and all its contents.
313
     *
314
     * @return void
315
     */
316
    protected function cleanupTempFolder()
317 70
    {
318
        $rootFolder = $this->fileSystemHelper->getRootFolder();
319 70
        $this->fileSystemHelper->deleteFolderRecursively($rootFolder);
320 70
    }
321
}
322