1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Eclipxe\XlsxExporter; |
6
|
|
|
|
7
|
|
|
use Eclipxe\XlsxExporter\Exceptions\InvalidDestinationFileException; |
8
|
|
|
use Eclipxe\XlsxExporter\Exceptions\TemporaryFileException; |
9
|
|
|
use Eclipxe\XlsxExporter\Exceptions\WorkBookCreateZipFileException; |
10
|
|
|
use Eclipxe\XlsxExporter\Exceptions\WorkBookWithoutWorkSheetsException; |
11
|
|
|
use Eclipxe\XlsxExporter\Exceptions\WorkBookWithRepeatedNamesException; |
12
|
|
|
use Eclipxe\XlsxExporter\Utils\TemporaryFile; |
13
|
|
|
|
14
|
|
|
class XlsxExporter |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* Save the workbook as a specified file |
18
|
|
|
* This is a shortcut for write, copy and unlink |
19
|
|
|
* |
20
|
|
|
* @throws WorkBookWithoutWorkSheetsException |
21
|
|
|
* @throws WorkBookWithRepeatedNamesException |
22
|
|
|
* @throws WorkBookCreateZipFileException |
23
|
|
|
* @throws TemporaryFileException |
24
|
|
|
* @throws InvalidDestinationFileException |
25
|
|
|
*/ |
26
|
1 |
|
public static function save(WorkBook $workbook, string $filename): void |
27
|
|
|
{ |
28
|
1 |
|
if (file_exists($filename) && is_dir($filename)) { |
29
|
|
|
throw InvalidDestinationFileException::isDirectory($filename); |
30
|
|
|
} |
31
|
1 |
|
if (! file_exists($filename) && ! is_dir(dirname($filename))) { |
32
|
|
|
throw InvalidDestinationFileException::existsAndParentisNotDirectory($filename); |
33
|
|
|
} |
34
|
1 |
|
$temporaryFile = new TemporaryFile('xslx-'); |
35
|
1 |
|
$workbook->write($temporaryFile); |
36
|
1 |
|
$temporaryFile->copy($filename); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Pass-tru the workbook and write the Content-type header |
41
|
|
|
* This is a shortcut for write, header, passtru and unlink |
42
|
|
|
* |
43
|
|
|
* @param WorkBook $workbook |
44
|
|
|
* |
45
|
|
|
* @throws WorkBookWithoutWorkSheetsException |
46
|
|
|
* @throws WorkBookWithRepeatedNamesException |
47
|
|
|
* @throws WorkBookCreateZipFileException |
48
|
|
|
* @throws TemporaryFileException |
49
|
|
|
*/ |
50
|
|
|
public static function passtru(WorkBook $workbook): void |
51
|
|
|
{ |
52
|
|
|
$temporaryFile = new TemporaryFile('xslx-'); |
53
|
|
|
$workbook->write($temporaryFile); |
54
|
|
|
header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); |
55
|
|
|
$temporaryFile->passthru(); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|