AbstractExporter   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 3
eloc 12
c 0
b 0
f 0
dl 0
loc 54
ccs 13
cts 13
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A export() 0 18 2
A __construct() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Application\Service\Exporter;
6
7
/**
8
 * @template T of \Application\Model\AbstractModel|array
9
 */
10
abstract class AbstractExporter
11
{
12
    private string $exportDir = 'htdocs/data/export/';
13
14 2
    public function __construct(
15
        protected string $hostname,
16 2
    ) {}
17
18
    abstract protected function getTitleForFilename(): string;
19
20
    abstract protected function getExtension(): string;
21
22
    /**
23
     * Initialize the export, possibly writing footer and closing file.
24
     */
25
    abstract protected function initialize(string $path): void;
26
27
    /**
28
     * Write the item, one per line, in the body part of the sheet.
29
     *
30
     * @param T $item
31
     */
32
    abstract protected function writeItem($item): void;
33
34
    /**
35
     * Finalize the export, possibly writing footer and closing file.
36
     */
37
    abstract protected function finalize(string $path): void;
38
39
    /**
40
     * Called by the field resolver or repository to generate a spreadsheet from the query builder.
41
     *
42
     * @param iterable<T> $items
43
     *
44
     * @return string the generated spreadsheet file path
45
     */
46 2
    public function export(iterable $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
57 2
        foreach ($items as $item) {
58 2
            $this->writeItem($item);
59
        }
60
61 2
        $this->finalize($path);
62
63 2
        return 'https://' . $this->hostname . '/data/export/' . $folder . $filename;
64
    }
65
}
66