Completed
Push — master ( c29061...fba80d )
by Tobias
05:40
created

WebUIController::indexAction()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 40
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 3
Bugs 0 Features 0
Metric Value
dl 0
loc 40
ccs 0
cts 34
cp 0
rs 8.439
c 3
b 0
f 0
cc 6
eloc 27
nc 7
nop 1
crap 42
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
        $config = $this->getConfiguration($configName);
42
        $localeMap = $this->getLocale2LanguageMap();
43
        $catalogues = $this->get('php_translation.catalogue_fetcher')->getCatalogues(array_keys($localeMap), [$config['output_dir']]);
44
45
        $catalogueSize = [];
46
        $maxDomainSize = [];
47
        $maxCatalogueSize = 1;
48
49
        // For each catalogue (or locale)
50
        /** @var MessageCatalogue $catalogue */
51
        foreach ($catalogues as $catalogue) {
52
            $locale = $catalogue->getLocale();
53
            $domains = $catalogue->all();
54
            ksort($domains);
55
            $catalogueSize[$locale] = 0;
56
            foreach ($domains as $domain => $messages) {
57
                $count = count($messages);
58
                $catalogueSize[$locale] += $count;
59
                if (!isset($maxDomainSize[$domain]) || $count > $maxDomainSize[$domain]) {
60
                    $maxDomainSize[$domain] = $count;
61
                }
62
            }
63
64
            if ($catalogueSize[$locale] > $maxCatalogueSize) {
65
                $maxCatalogueSize = $catalogueSize[$locale];
66
            }
67
        }
68
69
        return $this->render('TranslationBundle:WebUI:index.html.twig', [
70
            'catalogues' => $catalogues,
71
            'catalogueSize' => $catalogueSize,
72
            'maxDomainSize' => $maxDomainSize,
73
            'maxCatalogueSize' => $maxCatalogueSize,
74
            'localeMap' => $localeMap,
75
            'configName' => $configName,
76
            'configNames' => $this->get('php_translation.configuration_manager')->getNames(),
77
        ]);
78
    }
79
80
    /**
81
     * Show a catalogue.
82
     *
83
     * @param string $configName
84
     * @param string $locale
85
     * @param string $domain
86
     *
87
     * @return Response
88
     */
89
    public function showAction($configName, $locale, $domain)
90
    {
91
        $config = $this->getConfiguration($configName);
92
        $locales = $this->getParameter('php_translation.locales');
93
94
        // Get a catalogue manager and load it with all the catalogues
95
        $catalogueManager = $this->get('php_translation.catalogue_manager');
96
        $catalogueManager->load($this->get('php_translation.catalogue_fetcher')->getCatalogues($locales, [$config['output_dir']]));
97
98
        /** @var CatalogueMessage[] $messages */
99
        $messages = $catalogueManager->getMessages($locale, $domain);
100
        usort($messages, function (CatalogueMessage $a, CatalogueMessage $b) {
101
            return strcmp($a->getKey(), $b->getKey());
102
        });
103
104
        return $this->render('TranslationBundle:WebUI:show.html.twig', [
105
            'messages' => $messages,
106
            'domains' => $catalogueManager->getDomains(),
107
            'currentDomain' => $domain,
108
            'locales' => $locales,
109
            'currentLocale' => $locale,
110
            'configName' => $configName,
111
            'configNames' => $this->get('php_translation.configuration_manager')->getNames(),
112
        ]);
113
    }
114
115
    /**
116
     * @param Request $request
117
     * @param string  $configName
118
     * @param string  $locale
119
     * @param string  $domain
120
     *
121
     * @return Response
122
     */
123
    public function createAction(Request $request, $configName, $locale, $domain)
124
    {
125
        /** @var StorageService $storage */
126
        $storage = $this->get('php_translation.storage.'.$configName);
127
        try {
128
            $message = $this->getMessage($request, ['Create']);
129
        } catch (MessageValidationException $e) {
130
            return new Response($e->getMessage(), 400);
131
        }
132
133
        try {
134
            $storage->create(new Message($message->getKey(), $domain, $locale, $message->getMessage()));
135
        } catch (StorageException $e) {
136
            throw new BadRequestHttpException(sprintf(
137
                'Key "%s" does already exist for "%s" on domain "%s".',
138
                $message->getKey(),
139
                $locale,
140
                $domain
141
            ), $e);
142
        }
143
144
        return $this->render('TranslationBundle:WebUI:create.html.twig', [
145
            'message' => $message,
146
        ]);
147
    }
148
149
    /**
150
     * @param Request $request
151
     * @param string  $configName
152
     * @param string  $locale
153
     * @param string  $domain
154
     *
155
     * @return Response
156
     */
157 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...
158
    {
159
        try {
160
            $message = $this->getMessage($request, ['Edit']);
161
        } catch (MessageValidationException $e) {
162
            return new Response($e->getMessage(), 400);
163
        }
164
165
        /** @var StorageService $storage */
166
        $storage = $this->get('php_translation.storage.'.$configName);
167
        $storage->update(new Message($message->getKey(), $domain, $locale, $message->getMessage()));
168
169
        return new Response('Translation updated');
170
    }
171
172
    /**
173
     * @param Request $request
174
     * @param string  $configName
175
     * @param string  $locale
176
     * @param string  $domain
177
     *
178
     * @return Response
179
     */
180 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...
181
    {
182
        try {
183
            $message = $this->getMessage($request, ['Delete']);
184
        } catch (MessageValidationException $e) {
185
            return new Response($e->getMessage(), 400);
186
        }
187
188
        /** @var StorageService $storage */
189
        $storage = $this->get('php_translation.storage.'.$configName);
190
        $storage->delete($locale, $domain, $message->getKey());
191
192
        return new Response('Message was deleted');
193
    }
194
195
    /**
196
     * @param $configName
197
     *
198
     * @return array
199
     */
200
    private function getConfiguration(&$configName)
201
    {
202
        $configurationManager = $this->get('php_translation.configuration_manager');
203
        $configName = $configName !== null ? $configName : $configurationManager->getFirstName();
204
        if ($configName === null) {
205
            throw new \LogicException('You must configure at least one key under translation.configs');
206
        }
207
208
        $config = $configurationManager->getConfiguration($configName);
209
210
        if (empty($config)) {
211
            throw $this->createNotFoundException('No translation configuration named "'.$configName.'" was found.');
212
        }
213
214
        return $config;
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