Completed
Push — master ( 1af7e7...796d56 )
by Jeroen
16s
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\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
class TranslatorController extends AdminListController
27
{
28
    /**
29
     * @var AbstractAdminListConfigurator
30
     */
31
    private $adminListConfigurator;
32
33
    /**
34
     * @Route("/", name="KunstmaanTranslatorBundle_settings_translations")
35
     * @Template("KunstmaanTranslatorBundle:Translator:list.html.twig")
36
     *
37
     * @param \Symfony\Component\HttpFoundation\Request $request
38
     *
39
     * @return array
40
     */
41
    public function indexAction(Request $request)
42
    {
43
        $configurator = $this->getAdminListConfigurator();
44
45
        /* @var AdminList $adminList */
46
        $adminList = $this->container->get('kunstmaan_adminlist.factory')->createList($configurator);
47
        $adminList->bindRequest($request);
48
49
        $cacheFresh = $this->container->get('kunstmaan_translator.service.translator.cache_validator')->isCacheFresh();
50
        $debugMode = $this->container->getParameter('kuma_translator.debug') === true;
51
52
        if (!$cacheFresh && !$debugMode) {
53
            $this->addFlash(
54
                FlashTypes::INFO,
55
                $this->container->get('translator')->trans('settings.translator.not_live_warning')
56
            );
57
        }
58
59
        return [
60
            'adminlist' => $adminList,
61
            'adminlistconfigurator' => $configurator,
62
        ];
63
    }
64
65
    /**
66
     * @param Request $request
67
     * @param string                                    $keyword
68
     * @param string                                    $domain
69
     * @param string                                    $locale
70
     *
71
     * @return array|RedirectResponse
72
     * @throws \Doctrine\ORM\OptimisticLockException
73
     *
74
     * @Route("/add", name="KunstmaanTranslatorBundle_settings_translations_add")
75
     * @Method({"GET", "POST"})
76
     * @Template("KunstmaanTranslatorBundle:Translator:addTranslation.html.twig")
77
     */
78
    public function addAction(Request $request, $keyword = '', $domain = '', $locale = '')
79
    {
80
        /* @var $em EntityManager */
81
        $em = $this->getDoctrine()->getManager();
82
        $configurator = $this->getAdminListConfigurator();
83
        $translator = $this->container->get('translator');
84
85
        $translation = new \Kunstmaan\TranslatorBundle\Model\Translation();
86
        $locales = $this->container->getParameter('kuma_translator.managed_locales');
87
        foreach ($locales as $locale) {
88
            $translation->addText($locale, '');
89
        }
90
91
        $form = $this->createForm(TranslationAdminType::class, $translation, ['csrf_token_id' => 'add']);
92
        if ('POST' == $request->getMethod()) {
93
            $form->handleRequest($request);
94
95
            // Fetch form data
96
            $data = $form->getData();
97
            if (!$em->getRepository('KunstmaanTranslatorBundle:Translation')->isUnique($data)) {
98
                $error = new FormError($translator->trans('translator.translation_not_unique'));
99
                $form->get('domain')->addError($error);
100
                $form->get('keyword')->addError($error);
101
            }
102
103 View Code Duplication
            if ($form->isSubmitted() && $form->isValid()) {
104
                // Create translation
105
                $em->getRepository('KunstmaanTranslatorBundle:Translation')->createTranslations($data);
106
                $em->flush();
107
108
                $this->addFlash(
109
                    FlashTypes::SUCCESS,
110
                    $this->container->get('translator')->trans('settings.translator.succesful_added')
111
                );
112
113
                $indexUrl = $configurator->getIndexUrl();
114
115
                return new RedirectResponse($this->generateUrl(
116
                    $indexUrl['path'],
117
                    isset($indexUrl['params']) ? $indexUrl['params'] : []
118
                ));
119
            }
120
        }
121
122
        return [
123
            'form' => $form->createView(),
124
            'adminlistconfigurator' => $configurator,
125
        ];
126
    }
127
128
    /**
129
     * The edit action
130
     *
131
     * @Route("/{id}/edit", requirements={"id" = "\d+"}, name="KunstmaanTranslatorBundle_settings_translations_edit")
132
     * @Method({"GET", "POST"})
133
     * @Template("KunstmaanTranslatorBundle:Translator:editTranslation.html.twig")
134
     *
135
     * @param \Symfony\Component\HttpFoundation\Request $request
136
     * @param $id
137
     *
138
     * @throws \InvalidArgumentException
139
     *
140
     * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
141
     */
142
    public function editAction(Request $request, $id)
143
    {
144
        $em = $this->getDoctrine()->getManager();
145
        $configurator = $this->getAdminListConfigurator();
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()) {
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
0 ignored issues
show
Consider making the return type a bit more specific; maybe use array<string,\Symfony\Co...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...
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
     *
265
     * @throws NotFoundHttpException
266
     *
267
     * @Route("/{id}/delete", requirements={"id" = "\d+"}, name="KunstmaanTranslatorBundle_settings_translations_delete")
268
     * @Method({"GET", "POST"})
269
     */
270
    public function deleteAction(Request $request, $id)
271
    {
272
        /* @var $em EntityManager */
273
        $em = $this->getDoctrine()->getManager();
274
275
        $indexUrl = $this->getAdminListConfigurator()->getIndexUrl();
276
        if ($request->isMethod('POST')) {
277
            $em->getRepository('KunstmaanTranslatorBundle:Translation')->removeTranslations($id);
278
        }
279
280
        return new RedirectResponse($this->generateUrl($indexUrl['path'], isset($indexUrl['params']) ? $indexUrl['params'] : []));
281
    }
282
283
    /**
284
     * @param $adminListConfigurator
285
     */
286
    public function setAdminListConfigurator($adminListConfigurator)
287
    {
288
        $this->adminListConfigurator = $adminListConfigurator;
289
    }
290
291
    /**
292
     * @return AbstractAdminListConfigurator
293
     */
294
    public function getAdminListConfigurator()
295
    {
296
        $locales = $this->container->getParameter('kuma_translator.managed_locales');
297
298
        if (!isset($this->adminListConfigurator)) {
299
            $this->adminListConfigurator = new TranslationAdminListConfigurator($this->getDoctrine()->getConnection(), $locales);
300
        }
301
302
        return $this->adminListConfigurator;
303
    }
304
305
306
    /**
307
     * @param Request $request
308
     * @return JsonResponse|Response
309
     *
310
     * @Route("/inline-edit", name="KunstmaanTranslatorBundle_settings_translations_inline_edit")
311
     * @Method({"POST"})
312
     */
313
    public function inlineEditAction(Request $request)
314
    {
315
        $values = $request->request->all();
316
317
        $adminListConfigurator = $this->getAdminListConfigurator();
318
        if (!$adminListConfigurator->canEditInline($values)) {
319
            throw $this->createAccessDeniedException('Not allowed to edit this translation');
320
        }
321
322
        $id = isset($values['pk']) ? (int)$values['pk'] : 0;
323
        $em = $this->getDoctrine()->getManager();
324
        /**
325
         * @var TranslatorInterface
326
         */
327
        $translator = $this->container->get('translator');
328
329
        try {
330
            if ($id !== 0) {
331
                // Find existing translation
332
                $translation = $em->getRepository('KunstmaanTranslatorBundle:Translation')->find($id);
333
334
                if (is_null($translation)) {
335
                    return new Response($translator->trans('translator.translator.invalid_translation'), 500);
336
                }
337
            } else {
338
                // Create new translation
339
                $translation = new Translation();
340
                $translation->setDomain($values['domain']);
341
                $translation->setKeyword($values['keyword']);
342
                $translation->setLocale($values['locale']);
343
                $translation->setTranslationId($values['translationId']);
344
            }
345
            $translation->setText($values['value']);
346
            $em->persist($translation);
347
            $em->flush();
348
349
            return new JsonResponse([
350
                'success' => true,
351
                'uid' => $translation->getId(),
352
            ], 200);
353
        } catch (\Exception $e) {
354
            return new Response($translator->trans('translator.translator.fatal_error_occurred'), 500);
355
        }
356
    }
357
}
358