Completed
Pull Request — master (#8)
by Tobias
15:27 queued 07:58
created

WebUIController::createAction()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 22
ccs 0
cts 20
cp 0
rs 9.2
cc 3
eloc 16
nc 3
nop 4
crap 12
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\HttpKernel\Exception\HttpException;
19
use Symfony\Component\Intl\Intl;
20
use Symfony\Component\Translation\MessageCatalogue;
21
use Symfony\Component\Translation\Translator;
22
use Translation\Bundle\Exception\MessageValidationException;
23
use Translation\Bundle\Model\GuiMessageRepresentation;
24
use Translation\Common\Exception\StorageException;
25
use Translation\Symfony\Model\Message;
26
27
/**
28
 * @author Tobias Nyholm <[email protected]>
29
 */
30
class WebUIController extends Controller
31
{
32
    public function indexAction($configName = null)
33
    {
34
        $config = $this->getConfiguration($configName);
35
36
        $configuedLocales = $this->getParameter('php_translation.locales');
37
        $allLocales = Intl::getLocaleBundle()->getLocaleNames('en');
38
        $locales = [];
39
        foreach ($configuedLocales as $l) {
40
            $locales[$l] = $allLocales[$l];
41
        }
42
        $catalogues = $this->get('php_translation.catalogue_fetcher')->getCatalogues($configuedLocales, [$config['output_dir']]);
43
        $catalogueSize = [];
44
        $maxDomainSize = [];
45
        $maxCatalogueSize = 1;
46
        /** @var MessageCatalogue $catalogue */
47
        foreach ($catalogues as $catalogue) {
48
            $locale = $catalogue->getLocale();
49
            $domains = $catalogue->all();
50
            ksort($domains);
51
            $catalogueSize[$locale] = 0;
52
            foreach ($domains as $domain => $messages) {
53
                $count = count($messages);
54
                $catalogueSize[$locale] += $count;
55
                if (!isset($maxDomainSize[$domain]) || $count > $maxDomainSize[$domain]) {
56
                    $maxDomainSize[$domain] = $count;
57
                }
58
            }
59
60
            if ($catalogueSize[$locale] > $maxCatalogueSize) {
61
                $maxCatalogueSize = $catalogueSize[$locale];
62
            }
63
        }
64
65
        return $this->render('TranslationBundle:WebUI:index.html.twig', [
66
            'catalogues' => $catalogues,
67
            'catalogueSize' => $catalogueSize,
68
            'maxDomainSize' => $maxDomainSize,
69
            'maxCatalogueSize' => $maxCatalogueSize,
70
            'locales' => $locales,
71
            'configName' => $configName,
72
            'configNames' => $this->get('php_translation.configuration_manager')->getNames(),
73
        ]);
74
    }
75
76
    /**
77
     * @param $locale
78
     * @param $domain
79
     *
80
     * @return Response
81
     */
82
    public function showAction($configName, $locale, $domain)
83
    {
84
        $config = $this->getConfiguration($configName);
85
        $locales = $this->getParameter('php_translation.locales');
86
        /** @var Translator $translator */
87
        $catalogues = $this->get('php_translation.catalogue_fetcher')->getCatalogues($locales, [$config['output_dir']]);
88
        $catalogueManager = $this->get('php_translation.catalogue_manager');
89
        $catalogueManager->load($catalogues);
90
91
        /** @var Message[] $messages */
92
        $messages = $catalogueManager->getMessages($locale, $domain);
93
        usort($messages, function (Message $a, Message $b) {
94
            return strcmp($a->getKey(), $b->getKey());
95
        });
96
97
        return $this->render('TranslationBundle:WebUI:show.html.twig', [
98
            'messages' => $messages,
99
            'domains' => $catalogueManager->getDomains(),
100
            'currentDomain' => $domain,
101
            'locales' => $locales,
102
            'currentLocale' => $locale,
103
            'configName' => $configName,
104
            'configNames' => $this->get('php_translation.configuration_manager')->getNames(),
105
        ]);
106
    }
107
108
    /**
109
     * @param Request $request
110
     * @param string  $domain
111
     *
112
     * @return Response
113
     */
114
    public function createAction(Request $request, $configName, $locale, $domain)
115
    {
116
        $storage = $this->get('php_translation.storage.file.'.$configName);
117
        try {
118
            $message = $this->getMessage($request, ['Create']);
119
        } catch (MessageValidationException $e) {
120
            return new Response($e->getMessage(), 400);
121
        }
122
123
        try {
124
            $storage->set($locale, $domain, $message->getKey(), $message->getMessage());
125
        } catch (StorageException $e) {
126
            throw new BadRequestHttpException(sprintf(
127
                'Key "%s" does already exist for "%s" on domain "%s".',
128
                $message->getKey(),
129
                $locale,
130
                $domain
131
            ), $e);
132
        }
133
134
        return new Response('Translation created');
135
    }
136
137
    /**
138
     * @param Request $request
139
     * @param string  $configName
140
     * @param string  $locale
141
     * @param string  $domain
142
     *
143
     * @return Response
144
     */
145 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...
146
    {
147
        try {
148
            $message = $this->getMessage($request, ['Edit']);
149
        } catch (MessageValidationException $e) {
150
            return new Response($e->getMessage(), 400);
151
        }
152
153
        $this->get('php_translation.storage.file.'.$configName)->update($locale, $domain, $message->getKey(), $message->getMessage());
154
155
        return new Response('Translation updated');
156
    }
157
158
    /**
159
     * @param Request $request
160
     * @param string  $configName
161
     * @param string  $locale
162
     * @param string  $domain
163
     *
164
     * @return Response
165
     */
166 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...
167
    {
168
        try {
169
            $message = $this->getMessage($request, ['Delete']);
170
        } catch (MessageValidationException $e) {
171
            return new Response($e->getMessage(), 400);
172
        }
173
174
        $this->get('php_translation.storage.file.'.$configName)->delete($locale, $domain, $message->getKey());
175
176
        return new Response('Message was deleted');
177
    }
178
179
    /**
180
     * @param $configName
181
     *
182
     * @return array
183
     */
184
    private function getConfiguration(&$configName)
185
    {
186
        $configurationManager = $this->get('php_translation.configuration_manager');
187
        $configName = $configName !== null ? $configName : $configurationManager->getFirstName();
188
        if ($configName === null) {
189
            throw new \LogicException('You must configure at least one key under translation.config');
190
        }
191
192
        $config = $configurationManager->getConfiguration($configName);
193
194
        if (empty($config)) {
195
            throw $this->createNotFoundException('No translation configuration named "'.$configName.'" was found.');
196
        }
197
198
        return $config;
199
    }
200
201
    /**
202
     * @param Request $request
203
     * @param array $validationGroups
204
     *
205
     * @return GuiMessageRepresentation
206
     */
207
    private function getMessage(Request $request, array $validationGroups = [])
208
    {
209
        $json = $request->getContent();
210
        $data = json_decode($json, true);
211
        $message = new GuiMessageRepresentation();
212
        if (isset($data['key'])) {
213
            $message->setKey($data['key']);
214
        }
215
        if (isset($data['message'])) {
216
            $message->setMessage($data['message']);
217
        }
218
219
        $errors = $this->get('validator')->validate($message, null, $validationGroups);
220
        if (count($errors) > 0) {
221
            throw  MessageValidationException::create();
222
        }
223
224
        return $message;
225
    }
226
}
227