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