Passed
Push — master ( ec0d02...c0f595 )
by Jan
06:31 queued 10s
created

LabelController   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 113
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 58
c 3
b 0
f 0
dl 0
loc 113
rs 10
wmc 18

4 Methods

Rating   Name   Duplication   Size   Complexity  
C generator() 0 69 14
A getLabelName() 0 6 1
A findObjects() 0 11 2
A __construct() 0 8 1
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
namespace App\Controller;
22
23
24
use App\Entity\Base\AbstractDBElement;
25
use App\Entity\Contracts\NamedElementInterface;
26
use App\Entity\LabelSystem\LabelOptions;
27
use App\Entity\LabelSystem\LabelProfile;
28
use App\Entity\Parts\Part;
29
use App\Exceptions\TwigModeException;
30
use App\Form\LabelOptionsType;
31
use App\Form\LabelSystem\LabelDialogType;
32
use App\Helpers\LabelResponse;
33
use App\Repository\DBElementRepository;
34
use App\Services\ElementTypeNameGenerator;
35
use App\Services\LabelSystem\LabelGenerator;
36
use App\Services\Misc\RangeParser;
37
use Doctrine\ORM\EntityManagerInterface;
38
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
39
use Symfony\Component\Form\Form;
40
use Symfony\Component\Form\FormError;
41
use Symfony\Component\Form\SubmitButton;
42
use Symfony\Component\HttpFoundation\BinaryFileResponse;
43
use Symfony\Component\HttpFoundation\Request;
44
use Symfony\Component\HttpFoundation\Response;
45
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
46
use Symfony\Component\Routing\Annotation\Route;
47
use Symfony\Contracts\Translation\TranslatorInterface;
48
49
/**
50
 * @Route("/label")
51
 * @package App\Controller
52
 */
53
class LabelController extends AbstractController
54
{
55
    protected $labelGenerator;
56
    protected $em;
57
    protected $elementTypeNameGenerator;
58
    protected $rangeParser;
59
    protected $translator;
60
61
    public function __construct(LabelGenerator $labelGenerator, EntityManagerInterface $em, ElementTypeNameGenerator $elementTypeNameGenerator,
62
        RangeParser $rangeParser, TranslatorInterface $translator)
63
    {
64
        $this->labelGenerator = $labelGenerator;
65
        $this->em = $em;
66
        $this->elementTypeNameGenerator = $elementTypeNameGenerator;
67
        $this->rangeParser = $rangeParser;
68
        $this->translator = $translator;
69
    }
70
71
    /**
72
     * @Route("/dialog", name="label_dialog")
73
     * @Route("/{profile}/dialog", name="label_dialog_profile")
74
     */
75
    public function generator(Request $request, ?LabelProfile $profile = null)
76
    {
77
        $this->denyAccessUnlessGranted('@labels.create_labels');
78
79
        //If we inherit a LabelProfile, the user need to have access to it...
80
        if ($profile !== null) {
81
            $this->denyAccessUnlessGranted('read', $profile);
82
        }
83
84
        if ($profile) {
85
            $label_options = $profile->getOptions();
86
        } else {
87
            $label_options = new LabelOptions();
88
        }
89
90
        //We have to disable the options, if twig mode is selected and user is not allowed to use it.
91
        $disable_options = $label_options->getLinesMode() === 'twig' && !$this->isGranted("@labels.use_twig");
92
93
        $form = $this->createForm(LabelDialogType::class, null, [
94
            'disable_options' => $disable_options,
95
        ]);
96
97
        //Try to parse given target_type and target_id
98
        $target_type = $request->query->get('target_type', null);
99
        $target_id = $request->query->get('target_id', null);
100
        $generate = $request->query->getBoolean('generate', false);
101
102
        if ($profile === null && is_string($target_type)) {
103
            $label_options->setSupportedElement($target_type);
104
        }
105
        if (is_string($target_id)) {
106
            $form['target_id']->setData($target_id);
107
        }
108
109
110
        $form['options']->setData($label_options);
111
        $form->handleRequest($request);
112
113
        /** @var LabelOptions $form_options */
114
        $form_options = $form['options']->getData();
115
116
        $pdf_data = null;
117
        $filename = 'invalid.pdf';
118
119
        //Generate PDF either when the form is submitted and valid, or the form  was not submit yet, and generate is set
120
        if (($form->isSubmitted() && $form->isValid()) || ($generate && !$form->isSubmitted() && $profile !== null)) {
121
            $target_id = (string) $form->get('target_id')->getData();
122
            $targets = $this->findObjects($form_options->getSupportedElement(), $target_id);
123
            if (!empty($targets)) {
124
                try {
125
                    $pdf_data = $this->labelGenerator->generateLabel($form_options, $targets);
126
                    $filename = $this->getLabelName($targets[0], $profile);
127
                } catch (TwigModeException $exception) {
128
                    $form->get('options')->get('lines')->addError(new FormError($exception->getMessage()));
129
                }
130
131
            } else {
132
                //$this->addFlash('warning', 'label_generator.no_entities_found');
133
                $form->get('target_id')->addError(
134
                    new FormError($this->translator->trans('label_generator.no_entities_found'))
135
                );
136
            }
137
        }
138
139
        return $this->render('LabelSystem/dialog.html.twig', [
140
            'form' => $form->createView(),
141
            'pdf_data' => $pdf_data,
142
            'filename' => $filename,
143
            'profile' => $profile,
144
        ]);
145
    }
146
147
    protected function getLabelName(AbstractDBElement $element, ?LabelProfile $profile = null): string
148
    {
149
        $ret = 'label_' . $this->elementTypeNameGenerator->getLocalizedTypeLabel($element);
150
        $ret .= $element->getID();
151
152
        return $ret . '.pdf';
153
    }
154
155
    protected function findObjects(string $type, string $ids): array
156
    {
157
        if(!isset(LabelGenerator::CLASS_SUPPORT_MAPPING[$type])) {
158
            throw new \InvalidArgumentException('The given type is not known and can not be mapped to a class!');
159
        }
160
161
        $id_array = $this->rangeParser->parse($ids);
162
163
        /** @var DBElementRepository $repo */
164
        $repo = $this->em->getRepository(LabelGenerator::CLASS_SUPPORT_MAPPING[$type]);
165
        return $repo->getElementsFromIDArray($id_array);
166
    }
167
}