Passed
Push — master ( 1d79f0...af841a )
by Jan
03:19
created

ExportController::export()   B

Complexity

Conditions 9
Paths 70

Size

Total Lines 78
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 9
eloc 48
c 5
b 0
f 0
nc 70
nop 2
dl 0
loc 78
rs 7.5789

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Controller;
20
21
use App\Entity\BankAccount;
22
use App\Entity\PaymentOrder;
23
use App\Exception\SEPAExportAutoModeNotPossible;
24
use App\Form\SepaExportType;
25
use App\Helpers\ZIPBinaryFileResponseFacade;
26
use App\Services\PaymentOrdersSEPAExporter;
27
use Doctrine\ORM\EntityManagerInterface;
28
use RuntimeException;
29
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
30
use Symfony\Component\HttpFoundation\BinaryFileResponse;
31
use Symfony\Component\HttpFoundation\Request;
32
use Symfony\Component\HttpFoundation\Response;
33
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
34
use Symfony\Component\Routing\Annotation\Route;
35
use Symfony\Contracts\Translation\TranslatorInterface;
36
use ZipArchive;
37
38
/**
39
 * @Route("/admin/payment_order")
40
 */
41
class ExportController extends AbstractController
42
{
43
    protected $sepaExporter;
44
    protected $translator;
45
    protected $entityManager;
46
47
    public function __construct(PaymentOrdersSEPAExporter $sepaExporter, EntityManagerInterface $entityManager, TranslatorInterface $translator)
48
    {
49
        $this->sepaExporter = $sepaExporter;
50
        $this->translator = $translator;
51
        $this->entityManager = $entityManager;
52
    }
53
54
    /**
55
     * @Route("/export", name="payment_order_export")
56
     */
57
    public function export(Request $request, EntityManagerInterface $entityManager)
58
    {
59
        $this->denyAccessUnlessGranted('ROLE_EXPORT_PAYMENT_ORDERS');
60
61
        $ids = $request->query->get('ids');
62
        $id_array = explode(',', $ids);
63
        //Retrieve all payment orders which should be retrieved from DB:
64
        $payment_orders = [];
65
        foreach ($id_array as $id) {
66
            $payment_orders[] = $entityManager->find(PaymentOrder::class, $id);
67
        }
68
69
        $form = $this->createForm(SepaExportType::class);
70
71
        $form->handleRequest($request);
72
73
        if ($form->isSubmitted() && $form->isValid()) {
74
            //Determine the Values to use
75
            $data = $form->getData();
76
            //If user has selected a bank account preset, then use the data from it
77
            if ($data['bank_account'] instanceof BankAccount) {
78
                $iban = $data['bank_account']->getIban();
79
                $bic = $data['bank_account']->getBic();
80
                $name = $data['bank_account']->getExportAccountName();
81
            } else { //Use the manual inputted data
82
                $iban = $data['iban'];
83
                $bic = $data['bic'];
84
                $name = $data['name'];
85
            }
86
87
            try {
88
                $xml_files = $this->sepaExporter->export(
89
                    $payment_orders,
90
                    [
91
                        'iban' => $iban,
92
                        'bic' => $bic,
93
                        'name' => $name,
94
                        'mode' => $data['mode'],
95
                    ]
96
                );
97
98
                $response = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $response is dead and can be removed.
Loading history...
99
100
                //Download as file
101
                if (1 === count($xml_files)) {
102
                    $xml_string = array_values($xml_files)[0];
103
                    $filename = 'export_'.date('Y-m-d_H-i-s').'.xml';
104
                    $response = $this->getDownloadResponse($xml_string, $filename);
105
                } else {
106
                    $data = [];
107
                    foreach ($xml_files as $key => $content) {
108
                        $data[$key . '.xml'] = $content;
109
                    }
110
111
                    return ZIPBinaryFileResponseFacade::createZIPResponseFromData(
112
                        $data,
113
                        'export_'.date('Y-m-d_H-i-s').'.zip'
114
                    );
115
                }
116
117
                //Set export flag
118
                foreach ($payment_orders as $paymentOrder) {
119
                    $paymentOrder->setExported(true);
120
                }
121
                $this->entityManager->flush();
122
123
                return $response;
124
            } catch (SEPAExportAutoModeNotPossible $exception) {
125
                //Show error if auto mode is not possible
126
                $this->addFlash('danger',
127
                                $this->translator->trans('sepa_export.error.department_missing_account')
128
                                .': '.$exception->getWrongDepartment()->getName());
129
            }
130
        }
131
132
        return $this->render('admin/payment_order/export/export.html.twig', [
133
            'payment_orders' => $payment_orders,
134
            'form' => $form->createView(),
135
        ]);
136
    }
137
138
    protected function getDownloadResponse(string $content, string $filename, string $mime_type = 'application/xml'): Response
139
    {
140
        $response = new Response();
141
        $response->headers->set('Cache-Control', 'private');
142
        $response->headers->set('Content-type', $mime_type);
143
        $response->headers->set('Content-Disposition', 'attachment; filename="'.$filename.'";');
144
        $response->headers->set('Content-length', strlen($content));
145
        $response->setContent($content);
146
147
        return $response;
148
    }
149
}
150