Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
 
3
declare(strict_types=1);
4
 
5
namespace OpenSpout\Writer\Common\Manager;
6
 
7
use OpenSpout\Common\Entity\Row;
8
use OpenSpout\Common\Exception\InvalidArgumentException;
9
use OpenSpout\Common\Exception\IOException;
10
use OpenSpout\Common\Helper\StringHelper;
11
use OpenSpout\Writer\Common\AbstractOptions;
12
use OpenSpout\Writer\Common\Entity\Sheet;
13
use OpenSpout\Writer\Common\Entity\Workbook;
14
use OpenSpout\Writer\Common\Entity\Worksheet;
15
use OpenSpout\Writer\Common\Helper\FileSystemWithRootFolderHelperInterface;
16
use OpenSpout\Writer\Common\Manager\Style\StyleManagerInterface;
17
use OpenSpout\Writer\Common\Manager\Style\StyleMerger;
18
use OpenSpout\Writer\Exception\SheetNotFoundException;
19
 
20
/**
21
 * @internal
22
 */
23
abstract class AbstractWorkbookManager implements WorkbookManagerInterface
24
{
25
    protected WorksheetManagerInterface $worksheetManager;
26
 
27
    /** @var StyleManagerInterface Manages styles */
28
    protected StyleManagerInterface $styleManager;
29
 
30
    /** @var FileSystemWithRootFolderHelperInterface Helper to perform file system operations */
31
    protected FileSystemWithRootFolderHelperInterface $fileSystemHelper;
32
 
33
    protected AbstractOptions $options;
34
 
35
    /** @var Workbook The workbook to manage */
36
    private readonly Workbook $workbook;
37
 
38
    /** @var StyleMerger Helper to merge styles */
39
    private readonly StyleMerger $styleMerger;
40
 
41
    /** @var Worksheet The worksheet where data will be written to */
42
    private Worksheet $currentWorksheet;
43
 
44
    public function __construct(
45
        Workbook $workbook,
46
        AbstractOptions $options,
47
        WorksheetManagerInterface $worksheetManager,
48
        StyleManagerInterface $styleManager,
49
        StyleMerger $styleMerger,
50
        FileSystemWithRootFolderHelperInterface $fileSystemHelper
51
    ) {
52
        $this->workbook = $workbook;
53
        $this->options = $options;
54
        $this->worksheetManager = $worksheetManager;
55
        $this->styleManager = $styleManager;
56
        $this->styleMerger = $styleMerger;
57
        $this->fileSystemHelper = $fileSystemHelper;
58
    }
59
 
60
    /**
61
     * Creates a new sheet in the workbook and make it the current sheet.
62
     * The writing will resume where it stopped (i.e. data won't be truncated).
63
     *
64
     * @return Worksheet The created sheet
65
     */
66
    final public function addNewSheetAndMakeItCurrent(): Worksheet
67
    {
68
        $worksheet = $this->addNewSheet();
69
        $this->setCurrentWorksheet($worksheet);
70
 
71
        return $worksheet;
72
    }
73
 
74
    /**
75
     * @return Worksheet[] All the workbook's sheets
76
     */
77
    final public function getWorksheets(): array
78
    {
79
        return $this->workbook->getWorksheets();
80
    }
81
 
82
    /**
83
     * Returns the current sheet.
84
     *
85
     * @return Worksheet The current sheet
86
     */
87
    final public function getCurrentWorksheet(): Worksheet
88
    {
89
        return $this->currentWorksheet;
90
    }
91
 
92
    /**
93
     * Sets the given sheet as the current one. New data will be written to this sheet.
94
     * The writing will resume where it stopped (i.e. data won't be truncated).
95
     *
96
     * @param Sheet $sheet The "external" sheet to set as current
97
     *
98
     * @throws SheetNotFoundException If the given sheet does not exist in the workbook
99
     */
100
    final public function setCurrentSheet(Sheet $sheet): void
101
    {
102
        $worksheet = $this->getWorksheetFromExternalSheet($sheet);
103
        if (null !== $worksheet) {
104
            $this->currentWorksheet = $worksheet;
105
        } else {
106
            throw new SheetNotFoundException('The given sheet does not exist in the workbook.');
107
        }
108
    }
109
 
110
    /**
111
     * Adds a row to the current sheet.
112
     * If shouldCreateNewSheetsAutomatically option is set to true, it will handle pagination
113
     * with the creation of new worksheets if one worksheet has reached its maximum capicity.
114
     *
115
     * @param Row $row The row to be added
116
     *
117
     * @throws IOException              If trying to create a new sheet and unable to open the sheet for writing
118
     * @throws InvalidArgumentException
119
     */
120
    final public function addRowToCurrentWorksheet(Row $row): void
121
    {
122
        $currentWorksheet = $this->getCurrentWorksheet();
123
        if ($this->hasCurrentWorksheetReachedMaxRows()) {
124
            if (!$this->options->SHOULD_CREATE_NEW_SHEETS_AUTOMATICALLY) {
125
                return;
126
            }
127
 
128
            $currentWorksheet = $this->addNewSheetAndMakeItCurrent();
129
        }
130
 
131
        $this->addRowToWorksheet($currentWorksheet, $row);
132
        $currentWorksheet->getExternalSheet()->incrementWrittenRowCount();
133
    }
134
 
135
    /**
136
     * Closes the workbook and all its associated sheets.
137
     * All the necessary files are written to disk and zipped together to create the final file.
138
     * All the temporary files are then deleted.
139
     *
140
     * @param resource $finalFilePointer Pointer to the spreadsheet that will be created
141
     */
142
    final public function close($finalFilePointer): void
143
    {
144
        $this->closeAllWorksheets();
145
        $this->closeRemainingObjects();
146
        $this->writeAllFilesToDiskAndZipThem($finalFilePointer);
147
        $this->cleanupTempFolder();
148
    }
149
 
150
    /**
151
     * @return int Maximum number of rows/columns a sheet can contain
152
     */
153
    abstract protected function getMaxRowsPerWorksheet(): int;
154
 
155
    /**
156
     * Closes custom objects that are still opened.
157
     */
158
    protected function closeRemainingObjects(): void
159
    {
160
        // do nothing by default
161
    }
162
 
163
    /**
164
     * Writes all the necessary files to disk and zip them together to create the final file.
165
     *
166
     * @param resource $finalFilePointer Pointer to the spreadsheet that will be created
167
     */
168
    abstract protected function writeAllFilesToDiskAndZipThem($finalFilePointer): void;
169
 
170
    /**
171
     * @return string The file path where the data for the given sheet will be stored
172
     */
173
    private function getWorksheetFilePath(Sheet $sheet): string
174
    {
175
        $sheetsContentTempFolder = $this->fileSystemHelper->getSheetsContentTempFolder();
176
 
177
        return $sheetsContentTempFolder.\DIRECTORY_SEPARATOR.'sheet'.(1 + $sheet->getIndex()).'.xml';
178
    }
179
 
180
    /**
181
     * Deletes the root folder created in the temp folder and all its contents.
182
     */
183
    private function cleanupTempFolder(): void
184
    {
185
        $rootFolder = $this->fileSystemHelper->getRootFolder();
186
        $this->fileSystemHelper->deleteFolderRecursively($rootFolder);
187
    }
188
 
189
    /**
190
     * Creates a new sheet in the workbook. The current sheet remains unchanged.
191
     *
192
     * @return Worksheet The created sheet
193
     *
194
     * @throws IOException If unable to open the sheet for writing
195
     */
196
    private function addNewSheet(): Worksheet
197
    {
198
        $worksheets = $this->getWorksheets();
199
 
200
        $newSheetIndex = \count($worksheets);
201
        $sheetManager = new SheetManager(StringHelper::factory());
202
        $sheet = new Sheet($newSheetIndex, $this->workbook->getInternalId(), $sheetManager);
203
 
204
        $worksheetFilePath = $this->getWorksheetFilePath($sheet);
205
        $worksheet = new Worksheet($worksheetFilePath, $sheet);
206
 
207
        $this->worksheetManager->startSheet($worksheet);
208
 
209
        $worksheets[] = $worksheet;
210
        $this->workbook->setWorksheets($worksheets);
211
 
212
        return $worksheet;
213
    }
214
 
215
    private function setCurrentWorksheet(Worksheet $worksheet): void
216
    {
217
        $this->currentWorksheet = $worksheet;
218
    }
219
 
220
    /**
221
     * Returns the worksheet associated to the given external sheet.
222
     *
223
     * @return null|Worksheet the worksheet associated to the given external sheet or null if not found
224
     */
225
    private function getWorksheetFromExternalSheet(Sheet $sheet): ?Worksheet
226
    {
227
        $worksheetFound = null;
228
 
229
        foreach ($this->getWorksheets() as $worksheet) {
230
            if ($worksheet->getExternalSheet() === $sheet) {
231
                $worksheetFound = $worksheet;
232
 
233
                break;
234
            }
235
        }
236
 
237
        return $worksheetFound;
238
    }
239
 
240
    /**
241
     * @return bool whether the current worksheet has reached the maximum number of rows per sheet
242
     */
243
    private function hasCurrentWorksheetReachedMaxRows(): bool
244
    {
245
        $currentWorksheet = $this->getCurrentWorksheet();
246
 
247
        return $currentWorksheet->getLastWrittenRowIndex() >= $this->getMaxRowsPerWorksheet();
248
    }
249
 
250
    /**
251
     * Adds a row to the given sheet.
252
     *
253
     * @param Worksheet $worksheet Worksheet to write the row to
254
     * @param Row       $row       The row to be added
255
     *
256
     * @throws IOException
257
     * @throws InvalidArgumentException
258
     */
259
    private function addRowToWorksheet(Worksheet $worksheet, Row $row): void
260
    {
261
        $this->applyDefaultRowStyle($row);
262
        $this->worksheetManager->addRow($worksheet, $row);
263
 
264
        // update max num columns for the worksheet
265
        $currentMaxNumColumns = $worksheet->getMaxNumColumns();
266
        $cellsCount = $row->getNumCells();
267
        $worksheet->setMaxNumColumns(max($currentMaxNumColumns, $cellsCount));
268
    }
269
 
270
    private function applyDefaultRowStyle(Row $row): void
271
    {
272
        $mergedStyle = $this->styleMerger->merge(
273
            $row->getStyle(),
274
            $this->options->DEFAULT_ROW_STYLE
275
        );
276
        $row->setStyle($mergedStyle);
277
    }
278
 
279
    /**
280
     * Closes all workbook's associated sheets.
281
     */
282
    private function closeAllWorksheets(): void
283
    {
284
        $worksheets = $this->getWorksheets();
285
 
286
        foreach ($worksheets as $worksheet) {
287
            $this->worksheetManager->close($worksheet);
288
        }
289
    }
290
}