Completed
Push — master ( 584a71...a5bdca )
by Tobias
24:17 queued 18:42
created

WebUIController::createAction()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 33
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 5.3906

Importance

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