Writer::open()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 9
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
/**
4
 * This file is part of the bugloos/export-bundle project.
5
 * (c) Bugloos <https://bugloos.com/>
6
 * For the full copyright and license information, please view
7
 * the LICENSE file that was distributed with this source code.
8
 */
9
10
namespace Bugloos\ExportBundle;
11
12
use Bugloos\ExportBundle\Contracts\MultipleSheetsInterface;
13
use Bugloos\ExportBundle\Contracts\PropertiesInterface;
14
use PhpOffice\PhpSpreadsheet\IOFactory;
15
use PhpOffice\PhpSpreadsheet\Spreadsheet;
16
17
/**
18
 * @author Mojtaba Gheytasi <[email protected] | [email protected]>
19
 */
20
class Writer
21
{
22
    protected Spreadsheet $spreadsheet;
23
24
    public function export($export, string $writerType)
25
    {
26
        $this->open($export);
27
28
        $sheetExports = [$export];
29
30
        if ($export instanceof MultipleSheetsInterface) {
31
            $sheetExports = $export->sheets();
32
        }
33
34
        foreach ($sheetExports as $sheetExport) {
35
            $this->addNewSheet()->export($sheetExport);
36
        }
37
38
        return $this->write($writerType);
39
    }
40
41
    public function open($export): self
42
    {
43
        $this->spreadsheet = new Spreadsheet();
44
45
        $this->spreadsheet->disconnectWorksheets();
46
47
        $this->handleDocumentProperties($export);
48
49
        return $this;
50
    }
51
52
    public function write(string $writerType)
53
    {
54
        $this->spreadsheet->setActiveSheetIndex(0);
55
56
        $writer = IOFactory::createWriter($this->spreadsheet, $writerType);
57
58
        ob_start();
59
        $writer->save('php://output');
60
        $output = ob_get_clean();
61
62
        $this->spreadsheet->disconnectWorksheets();
63
        unset($this->spreadsheet);
64
65
        return $output;
66
    }
67
68
    public function addNewSheet(): Sheet
69
    {
70
        return new Sheet($this->spreadsheet->createSheet());
71
    }
72
73
    protected function handleDocumentProperties($export)
74
    {
75
        $properties = [];
76
77
        if ($export instanceof PropertiesInterface) {
78
            $properties = array_merge($properties, $export->properties());
79
        }
80
81
        $props = $this->spreadsheet->getProperties();
82
83
        foreach (array_filter($properties) as $property => $value) {
84
            $methodName = 'set'.ucfirst($property);
85
86
            $props->{$methodName}($value);
87
        }
88
    }
89
}
90