Completed
Push — master ( 046610...880e5c )
by Beñat
03:14 queued 12s
created

TranslateActionType   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 130
Duplicated Lines 8.46 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 21
lcom 1
cbo 1
dl 11
loc 130
rs 10
c 0
b 0
f 0

9 Methods

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