Completed
Pull Request — 5.6 (#2830)
by Jeroen
14:14
created

Controller/TranslatorController.php (1 issue)

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\Template;
15
use Symfony\Component\Form\FormBuilderInterface;
16
use Symfony\Component\Form\FormError;
17
use Symfony\Component\HttpFoundation\JsonResponse;
18
use Symfony\Component\HttpFoundation\RedirectResponse;
19
use Symfony\Component\HttpFoundation\Request;
20
use Symfony\Component\HttpFoundation\Response;
21
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
22
use Symfony\Component\Routing\Annotation\Route;
23
use Symfony\Component\Translation\TranslatorInterface;
24
25
class TranslatorController extends AdminListController
26
{
27
    /**
28
     * @var AbstractAdminListConfigurator
29
     */
30
    private $adminListConfigurator;
31
32
    /**
33
     * @Route("/", name="KunstmaanTranslatorBundle_settings_translations")
34
     * @Template("@KunstmaanTranslator/Translator/list.html.twig")
35
     *
36
     * @return array
0 ignored issues
show
Consider making the return type a bit more specific; maybe use array<string,AdminList|A...tAdminListConfigurator>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

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