Passed
Push — master ( 98831a...e4d06f )
by Jan
04:14
created

SEPAXMLExportResult::persistSEPAExports()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 4
rs 10
1
<?php
2
/*
3
 * Copyright (C) 2020  Jan Böhmer
4
 *
5
 * This program is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU Affero General Public License as published
7
 * by the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU Affero General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Affero General Public License
16
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17
 */
18
19
namespace App\Helpers\SEPAXML;
20
21
use App\Entity\SEPAExport;
22
use App\Helpers\ZIPBinaryFileResponseFacade;
23
use Doctrine\ORM\EntityManagerInterface;
24
use Symfony\Component\HttpFoundation\BinaryFileResponse;
25
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
26
27
final class SEPAXMLExportResult implements \Countable
28
{
29
    /** @var SEPAExport[] */
30
    private $sepa_exports;
31
32
    /**
33
     * @var array The options used for export
34
     */
35
    private $options;
36
37
    /**
38
     * @param  SEPAExport[]  $sepa_exports
39
     */
40
    public function __construct(array $sepa_exports, array $options)
41
    {
42
        if (count($sepa_exports) === 0) {
43
            throw new \InvalidArgumentException('$sepa_exports must not be empty!');
44
        }
45
46
        //Perform some checks on the sepa exports
47
        foreach($sepa_exports as $sepa_export) {
48
            if (!$sepa_export instanceof SEPAExport) {
49
                throw new \InvalidArgumentException('$sepa_exports must all be of type SEPAExport!');
50
            }
51
            if ($sepa_export->getXmlFile() === null) {
52
                throw new \InvalidArgumentException('Every Export in $sepa_exports must have an associated XML file!');
53
            }
54
        }
55
56
        $this->sepa_exports = $sepa_exports;
57
        $this->options = $options;
58
    }
59
60
    /**
61
     * Returns the number of SEPAExports contained
62
     * @return int|void
63
     */
64
    public function count()
65
    {
66
        return count($this->sepa_exports);
67
    }
68
69
    /**
70
     * Return the options array used to create this result
71
     * @return array
72
     */
73
    public function getOptions(): array
74
    {
75
        return $this->options;
76
    }
77
78
    /**
79
     * Returns the SEPA Exports contained in this result
80
     * @return SEPAExport[]
81
     */
82
    public function getSEPAExports(): array
83
    {
84
        return $this->sepa_exports;
85
    }
86
87
    /**
88
     * Returns an array of all XML files contained in this result.
89
     * The array keys contains suggested filenames for the files
90
     * @return \SplFileInfo[]
91
     */
92
    public function getXMLFiles(): array
93
    {
94
        $result = [];
95
96
        foreach ($this->sepa_exports as $sepa_export) {
97
            $filename = $this->generateFilename($sepa_export);
98
            //Ensure that filename is not existing yet (add an increment suffix)
99
            $i = 2;
100
            while (isset($result[$filename])) {
101
                $filename = basename($filename) . '_' . sprintf("%d", $i++) . '.xml';
102
            }
103
            $result[$filename] = $sepa_export->getXmlFile();
104
        }
105
106
        return $result;
107
    }
108
109
    /**
110
     * Returns an array of the contained XML files as strings.
111
     * The array keys contains suggested filenames for the files.
112
     * @return string[]
113
     */
114
    public function getXMLString(): array
115
    {
116
        $result = [];
117
        $files = $this->getXMLFiles();
118
119
        foreach ($files as $filename => $file) {
120
            $result[$filename] = file_get_contents($file->getPathname());
121
        }
122
123
        return $result;
124
    }
125
126
    /**
127
     * Generates a download response for the contained XML files. If only a single XML is contained, it will be downloaded
128
     * as XML file, otherwise as ZIP containing all files.
129
     * @param  string  $disposition_filename
130
     * @param  bool  $force_zip
131
     * @return BinaryFileResponse
132
     */
133
    public function getDownloadResponse(string $disposition_filename, bool $force_zip = false): BinaryFileResponse
134
    {
135
        //If we have only one file, we can just return the file
136
        if ($force_zip === false && $this->count() === 1) {
137
            $response = new BinaryFileResponse($this->sepa_exports[0]);
0 ignored issues
show
Bug introduced by
$this->sepa_exports[0] of type App\Entity\SEPAExport is incompatible with the type SplFileInfo|string expected by parameter $file of Symfony\Component\HttpFo...Response::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

137
            $response = new BinaryFileResponse(/** @scrutinizer ignore-type */ $this->sepa_exports[0]);
Loading history...
138
            $response->setPrivate();
139
            $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $disposition_filename);
140
        } else { //Otherwise we download the file as ZIP
141
            $response = ZIPBinaryFileResponseFacade::createZIPResponseFromFiles($this->getXMLFiles(), $disposition_filename);
142
        }
143
144
        return $response;
145
    }
146
147
    /**
148
     * Persist all contained SEPAExport entities using the given EntityManager.
149
     * @param  EntityManagerInterface  $entityManager
150
     * @return void
151
     */
152
    public function persistSEPAExports(EntityManagerInterface $entityManager): void
153
    {
154
        foreach($this->sepa_exports as $sepa_export) {
155
            $entityManager->persist($sepa_export);
156
        }
157
    }
158
159
    private function generateFilename(SEPAExport $export): string
160
    {
161
        return $export->getDescription() . '_' . $export->getCreationDate()->format('Y-M-D-His') . '.xml';
162
    }
163
}