Completed
Push — master ( 880e5c...11b970 )
by Beñat
04:35
created

NewTranslatableActionType   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 124
Duplicated Lines 24.19 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 18
lcom 1
cbo 1
dl 30
loc 124
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 13 13 1
C execute() 0 45 7
A checkFormIsPassed() 0 8 2
A checkLocaleIsAvailable() 0 8 2
A redirect() 0 18 2
A addError() 9 9 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
26
/**
27
 * @author Beñat Espiña <[email protected]>
28
 */
29
class NewTranslatableActionType implements ActionType
30
{
31
    private $flashBag;
32
    private $twig;
33
    private $formFactory;
34
    private $commandBus;
35
    private $urlGenerator;
36
37 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...
38
        FormFactoryInterface $formFactory,
39
        CommandBus $commandBus,
40
        \Twig_Environment $twig,
41
        FlashBagInterface $flashBag,
42
        UrlGeneratorInterface $urlGenerator
43
    ) {
44
        $this->twig = $twig;
45
        $this->flashBag = $flashBag;
46
        $this->formFactory = $formFactory;
47
        $this->commandBus = $commandBus;
48
        $this->urlGenerator = $urlGenerator;
49
    }
50
51
    public function execute($entity, Entity $config, Request $request, $options = null)
52
    {
53
        $entityName = $config->name();
54
        $locale = $request->query->get('locale');
55
56
        $this->checkFormIsPassed($options);
57
        $this->checkLocaleIsAvailable($locale);
58
59
        $form = $this->formFactory->create($options['form'], null, ['locale' => $locale]);
60
        if ($request->isMethod('POST') || $request->isMethod('PUT') || $request->isMethod('PATCH')) {
61
            $form->handleRequest($request);
62
            if ($form->isValid() && $form->isSubmitted()) {
63
                try {
64
                    $command = $form->getData();
65
                    $this->commandBus->handle($command);
66
67
                    $this->flashBag->add(
68
                        'lin3s_admin_success',
69
                        sprintf('The %s translation is successfully saved', $entityName)
70
                    );
71
72
                    return $this->redirect($options, $entityName, $command->id());
73
                } catch (Exception $exception) {
74
                    $this->addError($exception, $options);
75
                }
76
            } else {
77
                $this->flashBag->add(
78
                    'lin3s_admin_error',
79
                    sprintf(
80
                        'Errors while saving %s translation. Please check all fields and try again',
81
                        $entityName
82
                    )
83
                );
84
            }
85
        }
86
87
        return new Response(
88
            $this->twig->render('@Lin3sAdmin/Admin/form.html.twig', [
89
                'entity'       => $entity,
90
                'entityConfig' => $config,
91
                'locale'       => $locale,
92
                'form'         => $form->createView(),
93
            ])
94
        );
95
    }
96
97
    private function checkFormIsPassed($options)
98
    {
99
        if (!isset($options['form'])) {
100
            throw new \InvalidArgumentException(
101
                '"form" option is required so, you must declare inside action in the admin.yml'
102
            );
103
        }
104
    }
105
106
    private function checkLocaleIsAvailable($locale)
107
    {
108
        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...
109
            throw new NotFoundHttpException(
110
                sprintf('%s locale is not supported from the admin', $locale)
111
            );
112
        }
113
    }
114
115
    private function redirect($options, $entity, $id)
116
    {
117
        if (!isset($options['redirectAction'])) {
118
            return new RedirectResponse(
119
                $this->urlGenerator->generate('lin3s_admin_list', [
120
                    'entity' => $entity,
121
                ])
122
            );
123
        }
124
125
        return new RedirectResponse(
126
            $this->urlGenerator->generate('lin3s_admin_custom', [
127
                'action' => $options['redirectAction'],
128
                'entity' => $entity,
129
                'id'     => $id,
130
            ])
131
        );
132
    }
133
134 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...
135
    {
136
        $exceptions = $this->catchableExceptions($options);
137
        $exceptionClassName = get_class($exception);
138
139
        if (array_key_exists($exceptionClassName, $exceptions)) {
140
            $this->flashBag->add('lin3s_admin_error', $exceptions[$exceptionClassName]);
141
        }
142
    }
143
144 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...
145
    {
146
        if (!isset($options['catchable_exceptions'])) {
147
            return [];
148
        }
149
150
        return json_decode($options['catchable_exceptions'], true);
151
    }
152
}
153