Completed
Push — master ( 91fdab...75a7b9 )
by
unknown
13:37
created

Controller/TranslatorController.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Kunstmaan\TranslatorBundle\Controller;
4
5
use Doctrine\ORM\EntityManager;
6
use Kunstmaan\AdminBundle\FlashMessages\FlashTypes;
7
use Kunstmaan\AdminListBundle\AdminList\AdminList;
8
use Kunstmaan\AdminListBundle\AdminList\Configurator\AbstractAdminListConfigurator;
9
use Kunstmaan\AdminListBundle\Controller\AdminListController;
10
use Kunstmaan\TranslatorBundle\AdminList\TranslationAdminListConfigurator;
11
use Kunstmaan\TranslatorBundle\Entity\Translation;
12
use Kunstmaan\TranslatorBundle\Form\TranslationAdminType;
13
use Kunstmaan\TranslatorBundle\Form\TranslationsFileUploadType;
14
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
15
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
16
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
17
use Symfony\Component\Form\FormBuilderInterface;
18
use Symfony\Component\Form\FormError;
19
use Symfony\Component\HttpFoundation\JsonResponse;
20
use Symfony\Component\HttpFoundation\RedirectResponse;
21
use Symfony\Component\HttpFoundation\Request;
22
use Symfony\Component\HttpFoundation\Response;
23
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
24
use Symfony\Component\Translation\TranslatorInterface;
25
26
27
class TranslatorController extends AdminListController
28
{
29
30
    /**
31
     * @var AbstractAdminListConfigurator
32
     */
33
    private $adminListConfigurator;
34
35
36
    /**
37
     * @Route("/", name="KunstmaanTranslatorBundle_settings_translations")
38
     * @Template("KunstmaanTranslatorBundle:Translator:list.html.twig")
39
     *
40
     * @param \Symfony\Component\HttpFoundation\Request $request
41
     * @return array
42
     */
43
    public function indexAction(Request $request)
44
    {
45
        $configurator = $this->getAdminListConfigurator();
46
47
        /* @var AdminList $adminList */
48
        $adminList = $this->container->get("kunstmaan_adminlist.factory")->createList($configurator);
49
        $adminList->bindRequest($request);
50
51
        $cacheFresh = $this->container->get('kunstmaan_translator.service.translator.cache_validator')->isCacheFresh();
52
        $debugMode = $this->container->getParameter('kuma_translator.debug') === true;
53
54
        if (!$cacheFresh && !$debugMode) {
55
            $this->addFlash(
56
                FlashTypes::INFO,
57
                $this->container->get('translator')->trans('settings.translator.not_live_warning')
58
            );
59
        }
60
61
        return [
62
            'adminlist' => $adminList,
63
            'adminlistconfigurator' => $configurator,
64
        ];
65
    }
66
67
    /**
68
     * @param Request $request
69
     * @param string $keyword
70
     * @param string $domain
71
     * @param string $locale
72
     * @return array|RedirectResponse
73
     * @throws \Doctrine\ORM\OptimisticLockException
74
     *
75
     * @Route("/add", name="KunstmaanTranslatorBundle_settings_translations_add")
76
     * @Method({"GET", "POST"})
77
     * @Template("KunstmaanTranslatorBundle:Translator:addTranslation.html.twig")
78
     */
79
    public function addAction(Request $request, $keyword = '', $domain = '', $locale = '')
80
    {
81
        /* @var $em EntityManager */
82
        $em = $this->getDoctrine()->getManager();
83
        $configurator = $this->getAdminListConfigurator();
84
        $translator = $this->container->get('translator');
85
86
        $translation = new \Kunstmaan\TranslatorBundle\Model\Translation();
87
        $locales = $this->container->getParameter('kuma_translator.managed_locales');
88
        foreach ($locales as $locale) {
89
            $translation->addText($locale, '');
90
        }
91
92
        $form = $this->createForm(TranslationAdminType::class, $translation, ['csrf_token_id' => 'add']);
93
        if ('POST' == $request->getMethod()) {
94
            $form->handleRequest($request);
95
96
            // Fetch form data
97
            $data = $form->getData();
98
            if (!$em->getRepository('KunstmaanTranslatorBundle:Translation')->isUnique($data)) {
99
                $error = new FormError($translator->trans('translator.translation_not_unique'));
100
                $form->get('domain')->addError($error);
101
                $form->get('keyword')->addError($error);
102
            }
103
104 View Code Duplication
            if ($form->isSubmitted() && $form->isValid()) {
0 ignored issues
show
This code seems to be duplicated across 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...
105
                // Create translation
106
                $em->getRepository('KunstmaanTranslatorBundle:Translation')->createTranslations($data);
107
                $em->flush();
108
109
                $this->addFlash(
110
                    FlashTypes::SUCCESS,
111
                    $this->container->get('translator')->trans('settings.translator.succesful_added')
112
                );
113
114
                $indexUrl = $configurator->getIndexUrl();
115
116
                return new RedirectResponse($this->generateUrl(
117
                    $indexUrl['path'],
118
                    isset($indexUrl['params']) ? $indexUrl['params'] : []
119
                ));
120
            }
121
        }
122
123
        return [
124
            'form' => $form->createView(),
125
            'adminlistconfigurator' => $configurator,
126
        ];
127
    }
128
129
    /**
130
     * The edit action
131
     *
132
     * @Route("/{id}/edit", requirements={"id" = "\d+"}, name="KunstmaanTranslatorBundle_settings_translations_edit")
133
     * @Method({"GET", "POST"})
134
     * @Template("KunstmaanTranslatorBundle:Translator:editTranslation.html.twig")
135
     *
136
     * @param \Symfony\Component\HttpFoundation\Request $request
137
     * @param $id
138
     * @throws \InvalidArgumentException
139
     * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
140
     */
141
    public function editAction(Request $request, $id)
142
    {
143
        $em = $this->getDoctrine()->getManager();
144
        $configurator = $this->getAdminListConfigurator();
145
146
147
        $translations = $em->getRepository('KunstmaanTranslatorBundle:Translation')->findBy(['translationId' => $id]);
148
        if (count($translations) < 1) {
149
            throw new \InvalidArgumentException('No existing translations found for this id');
150
        }
151
152
        $translation = new \Kunstmaan\TranslatorBundle\Model\Translation();
153
        $translation->setDomain($translations[0]->getDomain());
154
        $translation->setKeyword($translations[0]->getKeyword());
155
        $locales = $this->container->getParameter('kuma_translator.managed_locales');
156
        foreach ($locales as $locale) {
157
            $found = false;
158
            foreach ($translations as $t) {
159
                if ($locale == $t->getLocale()) {
160
                    $translation->addText($locale, $t->getText(), $t->getId());
161
                    $found = true;
162
                }
163
            }
164
            if (!$found) {
165
                $translation->addText($locale, '');
166
            }
167
        }
168
169
        $form = $this->createForm(TranslationAdminType::class, $translation, ['intention' => 'edit']);
170
171
        if ('POST' == $request->getMethod()) {
172
            $form->handleRequest($request);
173
174 View Code Duplication
            if ($form->isSubmitted() && $form->isValid()) {
0 ignored issues
show
This code seems to be duplicated across 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...
175
                // Update translations
176
                $em->getRepository('KunstmaanTranslatorBundle:Translation')->updateTranslations($translation, $id);
177
                $em->flush();
178
179
                $this->addFlash(
180
                    FlashTypes::SUCCESS,
181
                    $this->container->get('translator')->trans('settings.translator.succesful_edited')
182
                );
183
184
                $indexUrl = $configurator->getIndexUrl();
185
186
                return new RedirectResponse($this->generateUrl(
187
                    $indexUrl['path'],
188
                    isset($indexUrl['params']) ? $indexUrl['params'] : []
189
                ));
190
            }
191
        }
192
193
        return [
194
            'form' => $form->createView(),
195
            'translation' => $translation,
196
            'adminlistconfigurator' => $configurator,
197
        ];
198
    }
199
200
    /**
201
     * @Route("upload", name="KunstmaanTranslatorBundle_settings_translations_upload")
202
     * @Method({"POST", "GET"})
203
     * @Template("KunstmaanTranslatorBundle:Translator:addTranslation.html.twig")
204
     *
205
     * @param Request $request
206
     * @return array
207
     */
208
    public function uploadFileAction(Request $request)
209
    {
210
        /** @var FormBuilderInterface $uploadForm */
211
        $form = $this->createForm(TranslationsFileUploadType::class);
212
        $configurator = $this->getAdminListConfigurator();
213
214
        if (Request::METHOD_POST === $request->getMethod()) {
215
            $form->handleRequest($request);
216
            if ($form->isSubmitted() && $form->isValid()) {
217
                $locales = explode('|', $this->container->getParameter('requiredlocales'));
218
                $data = $form->getData();
219
                $file = $data['file'];
220
                $force = $data['force'];
221
                $imported = $this->container->get('kunstmaan_translator.service.importer.importer')->importFromSpreadsheet($file, $locales, $force);
222
                $this->addFlash(FlashTypes::SUCCESS, sprintf("Translation imported: %d", $imported));
223
            }
224
        }
225
226
        return [
227
            'form' => $form->createView(),
228
            'adminlistconfigurator' => $configurator,
229
        ];
230
    }
231
232
    /**
233
     * @param $domain
234
     * @param $locale
235
     * @param $keyword
236
     * @return RedirectResponse
237
     *
238
     * @Method({"GET"})
239
     */
240
    public function editSearchAction($domain, $locale, $keyword)
241
    {
242
        $configurator = $this->getAdminListConfigurator();
243
        $em = $this->getDoctrine()->getManager();
244
        $translation = $em->getRepository('KunstmaanTranslatorBundle:Translation')->findOneBy(
245
            ['domain' => $domain, 'keyword' => $keyword, 'locale' => $locale]
246
        );
247
248
        if ($translation === null) {
249
            $addUrl = $configurator->getAddUrlFor(
250
                ['domain' => $domain, 'keyword' => $keyword, 'locale' => $locale]
251
            );
252
253
            return new RedirectResponse($this->generateUrl($addUrl['path'], $addUrl['params']));
254
        }
255
256
        $editUrl = $configurator->getEditUrlFor(['id' => $translation->getId()]);
257
258
        return new RedirectResponse($this->generateUrl($editUrl['path'], $editUrl['params']));
259
    }
260
261
    /**
262
     * @param $id
263
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
264
     * @throws NotFoundHttpException
265
     *
266
     * @Route("/{id}/delete", requirements={"id" = "\d+"}, name="KunstmaanTranslatorBundle_settings_translations_delete")
267
     * @Method({"GET", "POST"})
268
     */
269
    public function deleteAction(Request $request, $id)
270
    {
271
        /* @var $em EntityManager */
272
        $em = $this->getDoctrine()->getManager();
273
274
        $indexUrl = $this->getAdminListConfigurator()->getIndexUrl();
275
        if ($request->isMethod('POST')) {
276
            $em->getRepository('KunstmaanTranslatorBundle:Translation')->removeTranslations($id);
277
        }
278
279
        return new RedirectResponse($this->generateUrl($indexUrl['path'], isset($indexUrl['params']) ? $indexUrl['params'] : []));
280
    }
281
282
    /**
283
     * @param $adminListConfigurator
284
     */
285
    public function setAdminListConfigurator($adminListConfigurator)
286
    {
287
        $this->adminListConfigurator = $adminListConfigurator;
288
    }
289
290
    /**
291
     * @return AbstractAdminListConfigurator
292
     */
293
    public function getAdminListConfigurator()
294
    {
295
        $locales = $this->container->getParameter('kuma_translator.managed_locales');
296
297
        if (!isset($this->adminListConfigurator)) {
298
            $this->adminListConfigurator = new TranslationAdminListConfigurator($this->getDoctrine()->getConnection(), $locales);
299
        }
300
301
        return $this->adminListConfigurator;
302
    }
303
304
305
    /**
306
     * @param Request $request
307
     * @return JsonResponse|Response
308
     *
309
     * @Route("/inline-edit", name="KunstmaanTranslatorBundle_settings_translations_inline_edit")
310
     * @Method({"POST"})
311
     */
312
    public function inlineEditAction(Request $request)
313
    {
314
        $values = $request->request->all();
315
316
        $adminListConfigurator = $this->getAdminListConfigurator();
317
        if (!$adminListConfigurator->canEditInline($values)) {
318
            throw $this->createAccessDeniedException('Not allowed to edit this translation');
319
        }
320
321
        $id = isset($values['pk']) ? (int)$values['pk'] : 0;
322
        $em = $this->getDoctrine()->getManager();
323
        /**
324
         * @var TranslatorInterface $translator
325
         */
326
        $translator = $this->container->get('translator');
327
328
        try {
329
            if ($id !== 0) {
330
                // Find existing translation
331
                $translation = $em->getRepository('KunstmaanTranslatorBundle:Translation')->find($id);
332
333
                if (is_null($translation)) {
334
                    return new Response($translator->trans('translator.translator.invalid_translation'), 500);
335
                }
336
            } else {
337
                // Create new translation
338
                $translation = new Translation();
339
                $translation->setDomain($values['domain']);
340
                $translation->setKeyword($values['keyword']);
341
                $translation->setLocale($values['locale']);
342
                $translation->setTranslationId($values['translationId']);
343
            }
344
            $translation->setText($values['value']);
345
            $em->persist($translation);
346
            $em->flush();
347
348
            return new JsonResponse([
349
                'success' => true,
350
                'uid' => $translation->getId(),
351
            ], 200);
352
        } catch (\Exception $e) {
353
            return new Response($translator->trans('translator.translator.fatal_error_occurred'), 500);
354
        }
355
    }
356
}
357