Completed
Push — master ( 740372...dc5b6e )
by Tobias
10:09
created

WebUIController::showAction()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 30
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 2.0003

Importance

Changes 0
Metric Value
dl 0
loc 30
ccs 21
cts 22
cp 0.9545
rs 8.8571
c 0
b 0
f 0
cc 2
eloc 20
nc 2
nop 3
crap 2.0003
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
        ]);
122
    }
123
124
    /**
125
     * @param Request $request
126
     * @param string  $configName
127
     * @param string  $locale
128
     * @param string  $domain
129
     *
130
     * @return Response
131
     */
132 1
    public function createAction(Request $request, $configName, $locale, $domain)
133
    {
134 1
        if (!$this->getParameter('php_translation.webui.enabled') || !$this->getParameter('php_translation.webui.allow_create')) {
135
            return new Response('You are not allowed to create. Check you config. ', 400);
136
        }
137
138
        /** @var StorageService $storage */
139 1
        $storage = $this->get('php_translation.storage.'.$configName);
140
141
        try {
142 1
            $message = $this->getMessageFromRequest($request);
143 1
            $message->setDomain($domain);
144 1
            $message->setLocale($locale);
145 1
            $this->validateMessage($message, ['Create']);
146 1
        } catch (MessageValidationException $e) {
147 1
            return new Response($e->getMessage(), 400);
148
        }
149
150
        try {
151 1
            $storage->create($message);
152 1
        } catch (StorageException $e) {
153
            throw new BadRequestHttpException(sprintf(
154
                'Key "%s" does already exist for "%s" on domain "%s".',
155
                $message->getKey(),
156
                $locale,
157
                $domain
158
            ), $e);
159 1
        }
160
161 1
        return $this->render('TranslationBundle:WebUI:create.html.twig', [
162 1
            'message' => $message,
163 1
        ]);
164
    }
165
166
    /**
167
     * @param Request $request
168
     * @param string  $configName
169
     * @param string  $locale
170
     * @param string  $domain
171
     *
172
     * @return Response
173
     */
174 1
    public function editAction(Request $request, $configName, $locale, $domain)
175
    {
176 1
        if (!$this->getParameter('php_translation.webui.enabled')) {
177
            return new Response('You are not allowed here. Check you config. ', 400);
178
        }
179
180
        try {
181 1
            $message = $this->getMessageFromRequest($request);
182 1
            $message->setDomain($domain);
183 1
            $message->setLocale($locale);
184 1
            $this->validateMessage($message, ['Edit']);
185 1
        } catch (MessageValidationException $e) {
186 1
            return new Response($e->getMessage(), 400);
187
        }
188
189
        /** @var StorageService $storage */
190 1
        $storage = $this->get('php_translation.storage.'.$configName);
191 1
        $storage->update($message);
192
193 1
        return new Response('Translation updated');
194
    }
195
196
    /**
197
     * @param Request $request
198
     * @param string  $configName
199
     * @param string  $locale
200
     * @param string  $domain
201
     *
202
     * @return Response
203
     */
204 1
    public function deleteAction(Request $request, $configName, $locale, $domain)
205
    {
206 1
        if (!$this->getParameter('php_translation.webui.enabled') || !$this->getParameter('php_translation.webui.allow_delete')) {
207
            return new Response('You are not allowed to create. Check you config. ', 400);
208
        }
209
210
        try {
211 1
            $message = $this->getMessageFromRequest($request);
212 1
            $message->setLocale($locale);
213 1
            $message->setDomain($domain);
214 1
            $this->validateMessage($message, ['Delete']);
215 1
        } catch (MessageValidationException $e) {
216
            return new Response($e->getMessage(), 400);
217
        }
218
219
        /** @var StorageService $storage */
220 1
        $storage = $this->get('php_translation.storage.'.$configName);
221 1
        $storage->delete($locale, $domain, $message->getKey());
222
223 1
        return new Response('Message was deleted');
224
    }
225
226
    /**
227
     * @param Request $request
228
     *
229
     * @return Message
230
     */
231 3
    private function getMessageFromRequest(Request $request)
232
    {
233 3
        $json = $request->getContent();
234 3
        $data = json_decode($json, true);
235 3
        $message = new Message();
236 3
        if (isset($data['key'])) {
237 3
            $message->setKey($data['key']);
238 3
        }
239 3
        if (isset($data['message'])) {
240 2
            $message->setTranslation($data['message']);
241 2
        }
242
243 3
        return $message;
244
    }
245
246
    /**
247
     * This will return a map of our configured locales and their language name.
248
     *
249
     * @return array locale => language
250
     */
251 1
    private function getLocale2LanguageMap()
252
    {
253 1
        $configuedLocales = $this->getParameter('php_translation.locales');
254 1
        $names = Intl::getLocaleBundle()->getLocaleNames('en');
255 1
        $map = [];
256 1
        foreach ($configuedLocales as $l) {
257 1
            $map[$l] = $names[$l];
258 1
        }
259
260 1
        return $map;
261
    }
262
263
    /**
264
     * @param Message $message
265
     * @param array   $validationGroups
266
     *
267
     * @throws MessageValidationException
268
     */
269 3
    private function validateMessage(Message $message, array $validationGroups)
270
    {
271 3
        $errors = $this->get('validator')->validate($message, null, $validationGroups);
272 3
        if (count($errors) > 0) {
273 2
            throw  MessageValidationException::create();
274
        }
275 3
    }
276
}
277