Completed
Push — master ( bcebcf...1f9f52 )
by Tobias
06:16
created

WebUIController::deleteAction()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 18
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 18
loc 18
ccs 0
cts 12
cp 0
rs 9.2
c 0
b 0
f 0
cc 4
eloc 10
nc 3
nop 4
crap 20
1
<?php
2
3
/*
4
 * This file is part of the PHP Translation package.
5
 *
6
 * (c) PHP Translation team <[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 Translation\Bundle\Controller;
13
14
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
15
use Symfony\Component\HttpFoundation\Request;
16
use Symfony\Component\HttpFoundation\Response;
17
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
18
use Symfony\Component\Intl\Intl;
19
use Symfony\Component\Translation\MessageCatalogue;
20
use Translation\Bundle\Exception\MessageValidationException;
21
use Translation\Bundle\Model\WebUiMessage;
22
use Translation\Bundle\Service\StorageService;
23
use Translation\Common\Exception\StorageException;
24
use Translation\Bundle\Model\CatalogueMessage;
25
use Translation\Common\Model\Message;
26
27
/**
28
 * @author Tobias Nyholm <[email protected]>
29
 */
30
class WebUIController extends Controller
31
{
32
    /**
33
     * Show a dashboard for the configuration.
34
     *
35
     * @param string|null $configName
36
     *
37
     * @return Response
38
     */
39
    public function indexAction($configName = null)
40
    {
41
        if (!$this->getParameter('php_translation.webui.enabled')) {
42
            return new Response('You are not allowed here. Check you config. ', 400);
43
        }
44
45
        $configManager = $this->get('php_translation.configuration_manager');
46
        $config = $configManager->getConfiguration($configName);
47
        $localeMap = $this->getLocale2LanguageMap();
48
        $catalogues = $this->get('php_translation.catalogue_fetcher')->getCatalogues($config);
49
50
        $catalogueSize = [];
51
        $maxDomainSize = [];
52
        $maxCatalogueSize = 1;
53
54
        // For each catalogue (or locale)
55
        /** @var MessageCatalogue $catalogue */
56
        foreach ($catalogues as $catalogue) {
57
            $locale = $catalogue->getLocale();
58
            $domains = $catalogue->all();
59
            ksort($domains);
60
            $catalogueSize[$locale] = 0;
61
            foreach ($domains as $domain => $messages) {
62
                $count = count($messages);
63
                $catalogueSize[$locale] += $count;
64
                if (!isset($maxDomainSize[$domain]) || $count > $maxDomainSize[$domain]) {
65
                    $maxDomainSize[$domain] = $count;
66
                }
67
            }
68
69
            if ($catalogueSize[$locale] > $maxCatalogueSize) {
70
                $maxCatalogueSize = $catalogueSize[$locale];
71
            }
72
        }
73
74
        return $this->render('TranslationBundle:WebUI:index.html.twig', [
75
            'catalogues' => $catalogues,
76
            'catalogueSize' => $catalogueSize,
77
            'maxDomainSize' => $maxDomainSize,
78
            'maxCatalogueSize' => $maxCatalogueSize,
79
            'localeMap' => $localeMap,
80
            'configName' => $config->getName(),
81
            'configNames' => $configManager->getNames(),
82
        ]);
83
    }
84
85
    /**
86
     * Show a catalogue.
87
     *
88
     * @param string $configName
89
     * @param string $locale
90
     * @param string $domain
91
     *
92
     * @return Response
93
     */
94
    public function showAction($configName, $locale, $domain)
95
    {
96
        if (!$this->getParameter('php_translation.webui.enabled')) {
97
            return new Response('You are not allowed here. Check you config. ', 400);
98
        }
99
        $configManager = $this->get('php_translation.configuration_manager');
100
        $config = $configManager->getConfiguration($configName);
101
102
        // Get a catalogue manager and load it with all the catalogues
103
        $catalogueManager = $this->get('php_translation.catalogue_manager');
104
        $catalogueManager->load($this->get('php_translation.catalogue_fetcher')->getCatalogues($config));
105
106
        /** @var CatalogueMessage[] $messages */
107
        $messages = $catalogueManager->getMessages($locale, $domain);
108
        usort($messages, function (CatalogueMessage $a, CatalogueMessage $b) {
109
            return strcmp($a->getKey(), $b->getKey());
110
        });
111
112
        return $this->render('TranslationBundle:WebUI:show.html.twig', [
113
            'messages' => $messages,
114
            'domains' => $catalogueManager->getDomains(),
115
            'currentDomain' => $domain,
116
            'locales' => $this->getParameter('php_translation.locales'),
117
            'currentLocale' => $locale,
118
            'configName' => $config->getName(),
119
            'configNames' => $configManager->getNames(),
120
            'allow_create' => $this->getParameter('php_translation.webui.allow_create'),
121
            'allow_delete' => $this->getParameter('php_translation.webui.allow_delete'),
122
        ]);
123
    }
124
125
    /**
126
     * @param Request $request
127
     * @param string  $configName
128
     * @param string  $locale
129
     * @param string  $domain
130
     *
131
     * @return Response
132
     */
133
    public function createAction(Request $request, $configName, $locale, $domain)
134
    {
135
        if (!$this->getParameter('php_translation.webui.enabled') || !$this->getParameter('php_translation.webui.allow_create')) {
136
            return new Response('You are not allowed to create. Check you config. ', 400);
137
        }
138
139
        /** @var StorageService $storage */
140
        $storage = $this->get('php_translation.storage.'.$configName);
141
        try {
142
            $message = $this->getMessage($request, ['Create']);
143
        } catch (MessageValidationException $e) {
144
            return new Response($e->getMessage(), 400);
145
        }
146
147
        try {
148
            $storage->create(new Message($message->getKey(), $domain, $locale, $message->getMessage()));
149
        } catch (StorageException $e) {
150
            throw new BadRequestHttpException(sprintf(
151
                'Key "%s" does already exist for "%s" on domain "%s".',
152
                $message->getKey(),
153
                $locale,
154
                $domain
155
            ), $e);
156
        }
157
158
        return $this->render('TranslationBundle:WebUI:create.html.twig', [
159
            'message' => $message,
160
        ]);
161
    }
162
163
    /**
164
     * @param Request $request
165
     * @param string  $configName
166
     * @param string  $locale
167
     * @param string  $domain
168
     *
169
     * @return Response
170
     */
171 View Code Duplication
    public function editAction(Request $request, $configName, $locale, $domain)
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...
172
    {
173
        if (!$this->getParameter('php_translation.webui.enabled')) {
174
            return new Response('You are not allowed here. Check you config. ', 400);
175
        }
176
177
        try {
178
            $message = $this->getMessage($request, ['Edit']);
179
        } catch (MessageValidationException $e) {
180
            return new Response($e->getMessage(), 400);
181
        }
182
183
        /** @var StorageService $storage */
184
        $storage = $this->get('php_translation.storage.'.$configName);
185
        $storage->update(new Message($message->getKey(), $domain, $locale, $message->getMessage()));
186
187
        return new Response('Translation updated');
188
    }
189
190
    /**
191
     * @param Request $request
192
     * @param string  $configName
193
     * @param string  $locale
194
     * @param string  $domain
195
     *
196
     * @return Response
197
     */
198 View Code Duplication
    public function deleteAction(Request $request, $configName, $locale, $domain)
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...
199
    {
200
        if (!$this->getParameter('php_translation.webui.enabled') || !$this->getParameter('php_translation.webui.allow_delete')) {
201
            return new Response('You are not allowed to create. Check you config. ', 400);
202
        }
203
204
        try {
205
            $message = $this->getMessage($request, ['Delete']);
206
        } catch (MessageValidationException $e) {
207
            return new Response($e->getMessage(), 400);
208
        }
209
210
        /** @var StorageService $storage */
211
        $storage = $this->get('php_translation.storage.'.$configName);
212
        $storage->delete($locale, $domain, $message->getKey());
213
214
        return new Response('Message was deleted');
215
    }
216
217
    /**
218
     * @param Request $request
219
     * @param array   $validationGroups
220
     *
221
     * @return WebUiMessage
222
     */
223
    private function getMessage(Request $request, array $validationGroups = [])
224
    {
225
        $json = $request->getContent();
226
        $data = json_decode($json, true);
227
        $message = new WebUiMessage();
228
        if (isset($data['key'])) {
229
            $message->setKey($data['key']);
230
        }
231
        if (isset($data['message'])) {
232
            $message->setMessage($data['message']);
233
        }
234
235
        $errors = $this->get('validator')->validate($message, null, $validationGroups);
236
        if (count($errors) > 0) {
237
            throw  MessageValidationException::create();
238
        }
239
240
        return $message;
241
    }
242
243
    /**
244
     * This will return a map of our configured locales and their language name.
245
     *
246
     * @return array locale => language
247
     */
248
    private function getLocale2LanguageMap()
249
    {
250
        $configuedLocales = $this->getParameter('php_translation.locales');
251
        $names = Intl::getLocaleBundle()->getLocaleNames('en');
252
        $map = [];
253
        foreach ($configuedLocales as $l) {
254
            $map[$l] = $names[$l];
255
        }
256
257
        return $map;
258
    }
259
}
260