TranslateActionType::translatableId()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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