NewTranslatableActionType   A
last analyzed

Complexity

Total Complexity 18

Size/Duplication

Total Lines 128
Duplicated Lines 25.78 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 18
lcom 1
cbo 2
dl 33
loc 128
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 15 15 1
C execute() 0 45 7
A checkFormIsPassed() 0 8 2
A checkLocaleIsAvailable() 0 8 2
A redirect() 0 18 2
A addError() 10 10 2
A catchableExceptions() 8 8 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/*
4
 * This file is part of the CMS Kernel package.
5
 *
6
 * Copyright (c) 2016-present LIN3S <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace LIN3S\CMSKernel\Infrastructure\Lin3sAdminBundle\Action\Type;
13
14
use LIN3S\AdminBundle\Configuration\Model\Entity;
15
use LIN3S\AdminBundle\Configuration\Type\ActionType;
16
use LIN3S\SharedKernel\Application\CommandBus;
17
use LIN3S\SharedKernel\Exception\Exception;
18
use Symfony\Component\Form\FormFactoryInterface;
19
use Symfony\Component\HttpFoundation\RedirectResponse;
20
use Symfony\Component\HttpFoundation\Request;
21
use Symfony\Component\HttpFoundation\Response;
22
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
23
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
24
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
25
use Symfony\Component\Translation\TranslatorInterface;
26
27
/**
28
 * @author Beñat Espiña <[email protected]>
29
 */
30
class NewTranslatableActionType implements ActionType
31
{
32
    private $flashBag;
33
    private $twig;
34
    private $formFactory;
35
    private $commandBus;
36
    private $urlGenerator;
37
    private $translator;
38
39 View Code Duplication
    public function __construct(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
40
        FormFactoryInterface $formFactory,
41
        CommandBus $commandBus,
42
        \Twig_Environment $twig,
43
        FlashBagInterface $flashBag,
44
        UrlGeneratorInterface $urlGenerator,
45
        TranslatorInterface $translator
46
    ) {
47
        $this->twig = $twig;
48
        $this->flashBag = $flashBag;
49
        $this->formFactory = $formFactory;
50
        $this->commandBus = $commandBus;
51
        $this->urlGenerator = $urlGenerator;
52
        $this->translator = $translator;
53
    }
54
55
    public function execute($entity, Entity $config, Request $request, $options = null)
56
    {
57
        $entityName = $config->name();
58
        $locale = $request->query->get('locale');
59
60
        $this->checkFormIsPassed($options);
61
        $this->checkLocaleIsAvailable($locale);
62
63
        $form = $this->formFactory->create($options['form'], null, ['locale' => $locale]);
64
        if ($request->isMethod('POST') || $request->isMethod('PUT') || $request->isMethod('PATCH')) {
65
            $form->handleRequest($request);
66
            if ($form->isValid() && $form->isSubmitted()) {
67
                try {
68
                    $command = $form->getData();
69
                    $this->commandBus->handle($command);
70
71
                    $this->flashBag->add(
72
                        'lin3s_admin_success',
73
                        sprintf('The %s translation is successfully saved', $entityName)
74
                    );
75
76
                    return $this->redirect($options, $entityName, $command->id());
77
                } catch (Exception $exception) {
78
                    $this->addError($exception, $options);
79
                }
80
            } else {
81
                $this->flashBag->add(
82
                    'lin3s_admin_error',
83
                    sprintf(
84
                        'Errors while saving %s translation. Please check all fields and try again',
85
                        $entityName
86
                    )
87
                );
88
            }
89
        }
90
91
        return new Response(
92
            $this->twig->render('@Lin3sAdmin/Admin/form.html.twig', [
93
                'entity'       => $entity,
94
                'entityConfig' => $config,
95
                'locale'       => $locale,
96
                'form'         => $form->createView(),
97
            ])
98
        );
99
    }
100
101
    private function checkFormIsPassed($options)
102
    {
103
        if (!isset($options['form'])) {
104
            throw new \InvalidArgumentException(
105
                '"form" option is required so, you must declare inside action in the admin.yml'
106
            );
107
        }
108
    }
109
110
    private function checkLocaleIsAvailable($locale)
111
    {
112
        if (false) { // TODO: Check if locale is defined in the bundle configuration
0 ignored issues
show
Bug introduced by
Avoid IF statements that are always true or false
Loading history...
113
            throw new NotFoundHttpException(
114
                sprintf('%s locale is not supported from the admin', $locale)
115
            );
116
        }
117
    }
118
119
    private function redirect($options, $entity, $id)
120
    {
121
        if (!isset($options['redirectAction'])) {
122
            return new RedirectResponse(
123
                $this->urlGenerator->generate('lin3s_admin_list', [
124
                    'entity' => $entity,
125
                ])
126
            );
127
        }
128
129
        return new RedirectResponse(
130
            $this->urlGenerator->generate('lin3s_admin_custom', [
131
                'action' => $options['redirectAction'],
132
                'entity' => $entity,
133
                'id'     => $id,
134
            ])
135
        );
136
    }
137
138 View Code Duplication
    private function addError(Exception $exception, array $options)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
139
    {
140
        $exceptions = $this->catchableExceptions($options);
141
        $exceptionClassName = get_class($exception);
142
143
        if (array_key_exists($exceptionClassName, $exceptions)) {
144
            $error = $this->translator->trans($exceptions[$exceptionClassName]);
145
            $this->flashBag->add('lin3s_admin_error', $error);
146
        }
147
    }
148
149 View Code Duplication
    private function catchableExceptions(array $options)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
150
    {
151
        if (!isset($options['catchable_exceptions'])) {
152
            return [];
153
        }
154
155
        return json_decode($options['catchable_exceptions'], true);
156
    }
157
}
158