Passed
Push — master ( a4ee46...6ad24a )
by Jan
04:54
created

PartController::new()   F

Complexity

Conditions 23
Paths 10240

Size

Total Lines 89
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 23
eloc 57
nc 10240
nop 6
dl 0
loc 89
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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
 * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
4
 *
5
 * Copyright (C) 2019 - 2020 Jan Böhmer (https://github.com/jbtronics)
6
 *
7
 * This program is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU Affero General Public License as published
9
 * by the Free Software Foundation, either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License
18
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19
 */
20
21
declare(strict_types=1);
22
23
/**
24
 * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
25
 *
26
 * Copyright (C) 2019 Jan Böhmer (https://github.com/jbtronics)
27
 *
28
 * This program is free software; you can redistribute it and/or
29
 * modify it under the terms of the GNU General Public License
30
 * as published by the Free Software Foundation; either version 2
31
 * of the License, or (at your option) any later version.
32
 *
33
 * This program is distributed in the hope that it will be useful,
34
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
35
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
36
 * GNU General Public License for more details.
37
 *
38
 * You should have received a copy of the GNU General Public License
39
 * along with this program; if not, write to the Free Software
40
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
41
 */
42
43
namespace App\Controller;
44
45
use App\DataTables\LogDataTable;
46
use App\Entity\Parts\Category;
47
use App\Entity\Parts\Footprint;
48
use App\Entity\Parts\Part;
49
use App\Entity\Parts\PartLot;
50
use App\Entity\Parts\Storelocation;
51
use App\Entity\Parts\Supplier;
52
use App\Entity\PriceInformations\Orderdetail;
53
use App\Exceptions\AttachmentDownloadException;
54
use App\Form\Part\PartBaseType;
55
use App\Services\Attachments\AttachmentManager;
56
use App\Services\Attachments\AttachmentSubmitHandler;
57
use App\Services\Attachments\PartPreviewGenerator;
58
use App\Services\LogSystem\EventCommentHelper;
59
use App\Services\LogSystem\HistoryHelper;
60
use App\Services\LogSystem\TimeTravel;
61
use App\Services\Parameters\ParameterExtractor;
62
use App\Services\PricedetailHelper;
63
use Doctrine\ORM\EntityManagerInterface;
64
use Omines\DataTablesBundle\DataTableFactory;
65
use Proxies\__CG__\App\Entity\Parts\Manufacturer;
0 ignored issues
show
Bug introduced by
The type Proxies\__CG__\App\Entity\Parts\Manufacturer was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
66
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
67
use Symfony\Component\Form\FormInterface;
68
use Symfony\Component\HttpFoundation\RedirectResponse;
69
use Symfony\Component\HttpFoundation\Request;
70
use Symfony\Component\HttpFoundation\Response;
71
use Symfony\Component\Routing\Annotation\Route;
72
use Symfony\Contracts\Translation\TranslatorInterface;
73
74
/**
75
 * @Route("/part")
76
 */
77
class PartController extends AbstractController
78
{
79
    protected $attachmentManager;
80
    protected $pricedetailHelper;
81
    protected $partPreviewGenerator;
82
    protected $commentHelper;
83
84
    public function __construct(AttachmentManager $attachmentManager, PricedetailHelper $pricedetailHelper,
85
        PartPreviewGenerator $partPreviewGenerator, EventCommentHelper $commentHelper)
86
    {
87
        $this->attachmentManager = $attachmentManager;
88
        $this->pricedetailHelper = $pricedetailHelper;
89
        $this->partPreviewGenerator = $partPreviewGenerator;
90
        $this->commentHelper = $commentHelper;
91
    }
92
93
    /**
94
     * @Route("/{id}/info/{timestamp}", name="part_info")
95
     * @Route("/{id}", requirements={"id"="\d+"})
96
     *
97
     * @return Response
98
     *
99
     * @throws \Exception
100
     */
101
    public function show(Part $part, Request $request, TimeTravel $timeTravel, HistoryHelper $historyHelper,
102
        DataTableFactory $dataTable, ParameterExtractor $parameterExtractor, ?string $timestamp = null): Response
103
    {
104
        $this->denyAccessUnlessGranted('read', $part);
105
106
        $timeTravel_timestamp = null;
107
        if (null !== $timestamp) {
108
            $this->denyAccessUnlessGranted('@tools.timetravel');
109
            $this->denyAccessUnlessGranted('show_history', $part);
110
            //If the timestamp only contains numbers interpret it as unix timestamp
111
            if (ctype_digit($timestamp)) {
112
                $timeTravel_timestamp = new \DateTime();
113
                $timeTravel_timestamp->setTimestamp((int) $timestamp);
114
            } else { //Try to parse it via DateTime
115
                $timeTravel_timestamp = new \DateTime($timestamp);
116
            }
117
            $timeTravel->revertEntityToTimestamp($part, $timeTravel_timestamp);
118
        }
119
120
        if ($this->isGranted('show_history', $part)) {
121
            $table = $dataTable->createFromType(LogDataTable::class, [
122
                'filter_elements' => $historyHelper->getAssociatedElements($part),
123
                'mode' => 'element_history',
124
            ], ['pageLength' => 10])
125
                ->handleRequest($request);
126
127
            if ($table->isCallback()) {
128
                return $table->getResponse();
129
            }
130
        } else {
131
            $table = null;
132
        }
133
134
        return $this->render(
135
            'Parts/info/show_part_info.html.twig',
136
            [
137
                'part' => $part,
138
                'datatable' => $table,
139
                'attachment_helper' => $this->attachmentManager,
140
                'pricedetail_helper' => $this->pricedetailHelper,
141
                'pictures' => $this->partPreviewGenerator->getPreviewAttachments($part),
142
                'timeTravel' => $timeTravel_timestamp,
143
                'description_params' => $parameterExtractor->extractParameters($part->getDescription()),
144
                'comment_params' => $parameterExtractor->extractParameters($part->getComment()),
145
            ]
146
        );
147
    }
148
149
    /**
150
     * @Route("/{id}/edit", name="part_edit")
151
     *
152
     * @return Response
153
     */
154
    public function edit(Part $part, Request $request, EntityManagerInterface $em, TranslatorInterface $translator,
155
        AttachmentSubmitHandler $attachmentSubmitHandler): Response
156
    {
157
        $this->denyAccessUnlessGranted('edit', $part);
158
159
        $form = $this->createForm(PartBaseType::class, $part);
160
161
        $form->handleRequest($request);
162
        if ($form->isSubmitted() && $form->isValid()) {
163
            //Upload passed files
164
            $attachments = $form['attachments'];
165
            foreach ($attachments as $attachment) {
166
                /** @var FormInterface $attachment */
167
                $options = [
168
                    'secure_attachment' => $attachment['secureFile']->getData(),
169
                    'download_url' => $attachment['downloadURL']->getData(),
170
                ];
171
172
                try {
173
                    $attachmentSubmitHandler->handleFormSubmit($attachment->getData(), $attachment['file']->getData(), $options);
174
                } catch (AttachmentDownloadException $attachmentDownloadException) {
175
                    $this->addFlash(
176
                        'error',
177
                        $translator->trans('attachment.download_failed').' '.$attachmentDownloadException->getMessage()
178
                    );
179
                }
180
            }
181
182
            $this->commentHelper->setMessage($form['log_comment']->getData());
183
184
            $em->persist($part);
185
            $em->flush();
186
            $this->addFlash('info', 'part.edited_flash');
187
            //Reload form, so the SIUnitType entries use the new part unit
188
            $form = $this->createForm(PartBaseType::class, $part);
189
        } elseif ($form->isSubmitted() && ! $form->isValid()) {
190
            $this->addFlash('error', 'part.edited_flash.invalid');
191
        }
192
193
        return $this->render('Parts/edit/edit_part_info.html.twig',
194
                             [
195
                                 'part' => $part,
196
                                 'form' => $form->createView(),
197
                                 'attachment_helper' => $this->attachmentManager,
198
                             ]);
199
    }
200
201
    /**
202
     * @Route("/{id}/delete", name="part_delete", methods={"DELETE"})
203
     *
204
     * @return RedirectResponse
205
     */
206
    public function delete(Request $request, Part $part): RedirectResponse
207
    {
208
        $this->denyAccessUnlessGranted('delete', $part);
209
210
        if ($this->isCsrfTokenValid('delete'.$part->getId(), $request->request->get('_token'))) {
211
            $entityManager = $this->getDoctrine()->getManager();
212
213
            $this->commentHelper->setMessage($request->request->get('log_comment', null));
214
215
            //Remove part
216
            $entityManager->remove($part);
217
218
            //Flush changes
219
            $entityManager->flush();
220
221
            $this->addFlash('success', 'part.deleted');
222
        }
223
224
        return $this->redirectToRoute('homepage');
225
    }
226
227
    /**
228
     * @Route("/new", name="part_new")
229
     * @Route("/{id}/clone", name="part_clone")
230
     *
231
     * @return Response
232
     */
233
    public function new(Request $request, EntityManagerInterface $em, TranslatorInterface $translator,
234
        AttachmentManager $attachmentHelper, AttachmentSubmitHandler $attachmentSubmitHandler, ?Part $part = null): Response
235
    {
236
        if (null === $part) {
237
            $new_part = new Part();
238
        } else {
239
            $new_part = clone $part;
240
        }
241
242
        $this->denyAccessUnlessGranted('create', $new_part);
243
244
        $cid = $request->get('category', null);
245
        $category = $cid ? $em->find(Category::class, $cid) : null;
246
        if (null !== $category && null === $new_part->getCategory()) {
247
            $new_part->setCategory($category);
248
        }
249
250
        $fid = $request->get('footprint', null);
251
        $footprint = $fid ? $em->find(Footprint::class, $cid) : null;
252
        if (null !== $footprint && null === $new_part->getFootprint()) {
253
            $new_part->setFootprint($footprint);
254
        }
255
256
        $mid = $request->get('manufacturer', null);
257
        $manufacturer = $mid ? $em->find(Manufacturer::class, $mid) : null;
258
        if (null !== $manufacturer && null === $new_part->getManufacturer()) {
259
            $new_part->setManufacturer($manufacturer);
260
        }
261
262
        $store_id = $request->get('storelocation', null);
263
        $storelocation = $store_id ? $em->find(Storelocation::class, $store_id): null;
264
        if (null !== $storelocation && $new_part->getPartLots()->isEmpty()) {
265
            $partLot = new PartLot();
266
            $partLot->setStorageLocation($storelocation);
267
            $partLot->setInstockUnknown(true);
268
            $new_part->addPartLot($partLot);
269
        }
270
271
        $supplier_id = $request->get('supplier', null);
272
        $supplier = $supplier_id ? $em->find(Supplier::class, $supplier_id): null;
273
        if (null !== $supplier && $new_part->getOrderdetails()->isEmpty()) {
274
            $orderdetail = new Orderdetail();
275
            $orderdetail->setSupplier($supplier);
276
            $new_part->addOrderdetail($orderdetail);
277
        }
278
279
280
        $form = $this->createForm(PartBaseType::class, $new_part);
281
282
        $form->handleRequest($request);
283
284
        if ($form->isSubmitted() && $form->isValid()) {
285
            //Upload passed files
286
            $attachments = $form['attachments'];
287
            foreach ($attachments as $attachment) {
288
                /** @var FormInterface $attachment */
289
                $options = [
290
                    'secure_attachment' => $attachment['secureFile']->getData(),
291
                    'download_url' => $attachment['downloadURL']->getData(),
292
                ];
293
294
                try {
295
                    $attachmentSubmitHandler->handleFormSubmit($attachment->getData(), $attachment['file']->getData(), $options);
296
                } catch (AttachmentDownloadException $attachmentDownloadException) {
297
                    $this->addFlash(
298
                        'error',
299
                        $translator->trans('attachment.download_failed').' '.$attachmentDownloadException->getMessage()
300
                    );
301
                }
302
            }
303
304
            $this->commentHelper->setMessage($form['log_comment']->getData());
305
306
            $em->persist($new_part);
307
            $em->flush();
308
            $this->addFlash('success', 'part.created_flash');
309
310
            return $this->redirectToRoute('part_edit', ['id' => $new_part->getID()]);
311
        }
312
313
        if ($form->isSubmitted() && ! $form->isValid()) {
314
            $this->addFlash('error', 'part.created_flash.invalid');
315
        }
316
317
        return $this->render('Parts/edit/new_part.html.twig',
318
                             [
319
                                 'part' => $new_part,
320
                                 'form' => $form->createView(),
321
                                 'attachment_helper' => $attachmentHelper,
322
                             ]);
323
    }
324
}
325