1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Application\Service\Exporter; |
6
|
|
|
|
7
|
|
|
use Application\Model\AbstractModel; |
8
|
|
|
|
9
|
|
|
abstract class AbstractExporter |
10
|
|
|
{ |
11
|
|
|
private string $exportDir = 'htdocs/data/export/'; |
12
|
|
|
|
13
|
|
|
protected string $hostname; |
14
|
|
|
|
15
|
2 |
|
public function __construct(string $hostname) |
16
|
|
|
{ |
17
|
2 |
|
$this->hostname = $hostname; |
18
|
2 |
|
} |
19
|
|
|
|
20
|
|
|
abstract protected function getTitleForFilename(): string; |
21
|
|
|
|
22
|
|
|
abstract protected function getExtension(): string; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Initialize the export, possibly writing footer and closing file |
26
|
|
|
*/ |
27
|
|
|
abstract protected function initialize(string $path): void; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Write the items, one per line, in the body part of the sheet |
31
|
|
|
* |
32
|
|
|
* @param AbstractModel[] $items |
33
|
|
|
*/ |
34
|
|
|
abstract protected function writeData(array $items): void; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Finalize the export, possibly writing footer and closing file |
38
|
|
|
*/ |
39
|
|
|
abstract protected function finalize(string $path): void; |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Called by the field resolver or repository to generate a spreadsheet from the query builder |
43
|
|
|
* |
44
|
|
|
* @return string the generated spreadsheet file path |
45
|
|
|
*/ |
46
|
2 |
|
public function export(array $items): string |
47
|
|
|
{ |
48
|
2 |
|
$folder = bin2hex(random_bytes(16)) . '/'; |
49
|
2 |
|
$dir = $this->exportDir . $folder; |
50
|
2 |
|
mkdir($dir); |
51
|
|
|
|
52
|
2 |
|
$filename = $this->getTitleForFilename() . '.' . $this->getExtension(); |
53
|
2 |
|
$path = $dir . $filename; |
54
|
|
|
|
55
|
2 |
|
$this->initialize($path); |
56
|
2 |
|
$this->writeData($items); |
57
|
2 |
|
$this->finalize($path); |
58
|
|
|
|
59
|
2 |
|
return 'https://' . $this->hostname . '/data/export/' . $folder . $filename; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|