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
     *
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()) {
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
     *
139
     * @throws \InvalidArgumentException
140
     *
141
     * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
142
     */
143
    public function editAction(Request $request, $id)
144
    {
145
        $em = $this->getDoctrine()->getManager();
146
        $configurator = $this->getAdminListConfigurator();
147
148
        $translations = $em->getRepository('KunstmaanTranslatorBundle:Translation')->findBy(['translationId' => $id]);
149
        if (count($translations) < 1) {
150
            throw new \InvalidArgumentException('No existing translations found for this id');
151
        }
152
153
        $translation = new \Kunstmaan\TranslatorBundle\Model\Translation();
154
        $translation->setDomain($translations[0]->getDomain());
155
        $translation->setKeyword($translations[0]->getKeyword());
156
        $locales = $this->container->getParameter('kuma_translator.managed_locales');
157
        foreach ($locales as $locale) {
158
            $found = false;
159
            foreach ($translations as $t) {
160
                if ($locale == $t->getLocale()) {
161
                    $translation->addText($locale, $t->getText(), $t->getId());
162
                    $found = true;
163
                }
164
            }
165
            if (!$found) {
166
                $translation->addText($locale, '');
167
            }
168
        }
169
170
        $form = $this->createForm(TranslationAdminType::class, $translation, ['intention' => 'edit']);
171
172
        if ('POST' == $request->getMethod()) {
173
            $form->handleRequest($request);
174
175 View Code Duplication
            if ($form->isSubmitted() && $form->isValid()) {
176
                // Update translations
177
                $em->getRepository('KunstmaanTranslatorBundle:Translation')->updateTranslations($translation, $id);
178
                $em->flush();
179
180
                $this->addFlash(
181
                    FlashTypes::SUCCESS,
182
                    $this->container->get('translator')->trans('settings.translator.succesful_edited')
183
                );
184
185
                $indexUrl = $configurator->getIndexUrl();
186
187
                return new RedirectResponse($this->generateUrl(
188
                    $indexUrl['path'],
189
                    isset($indexUrl['params']) ? $indexUrl['params'] : []
190
                ));
191
            }
192
        }
193
194
        return [
195
            'form' => $form->createView(),
196
            'translation' => $translation,
197
            'adminlistconfigurator' => $configurator,
198
        ];
199
    }
200
201
    /**
202
     * @Route("upload", name="KunstmaanTranslatorBundle_settings_translations_upload")
203
     * @Method({"POST", "GET"})
204
     * @Template("KunstmaanTranslatorBundle:Translator:addTranslation.html.twig")
205
     *
206
     * @param Request $request
207
     *
208
     * @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...
209
     */
210
    public function uploadFileAction(Request $request)
211
    {
212
        /** @var FormBuilderInterface $uploadForm */
213
        $form = $this->createForm(TranslationsFileUploadType::class);
214
        $configurator = $this->getAdminListConfigurator();
215
216
        if (Request::METHOD_POST === $request->getMethod()) {
217
            $form->handleRequest($request);
218
            if ($form->isSubmitted() && $form->isValid()) {
219
                $locales = explode('|', $this->container->getParameter('requiredlocales'));
220
                $data = $form->getData();
221
                $file = $data['file'];
222
                $force = $data['force'];
223
                $imported = $this->container->get('kunstmaan_translator.service.importer.importer')->importFromSpreadsheet($file, $locales, $force);
224
                $this->addFlash(FlashTypes::SUCCESS, sprintf('Translation imported: %d', $imported));
225
            }
226
        }
227
228
        return [
229
            'form' => $form->createView(),
230
            'adminlistconfigurator' => $configurator,
231
        ];
232
    }
233
234
    /**
235
     * @param $domain
236
     * @param $locale
237
     * @param $keyword
238
     *
239
     * @return RedirectResponse
240
     *
241
     * @Method({"GET"})
242
     */
243
    public function editSearchAction($domain, $locale, $keyword)
244
    {
245
        $configurator = $this->getAdminListConfigurator();
246
        $em = $this->getDoctrine()->getManager();
247
        $translation = $em->getRepository('KunstmaanTranslatorBundle:Translation')->findOneBy(
248
            ['domain' => $domain, 'keyword' => $keyword, 'locale' => $locale]
249
        );
250
251
        if ($translation === null) {
252
            $addUrl = $configurator->getAddUrlFor(
253
                ['domain' => $domain, 'keyword' => $keyword, 'locale' => $locale]
254
            );
255
256
            return new RedirectResponse($this->generateUrl($addUrl['path'], $addUrl['params']));
257
        }
258
259
        $editUrl = $configurator->getEditUrlFor(['id' => $translation->getId()]);
260
261
        return new RedirectResponse($this->generateUrl($editUrl['path'], $editUrl['params']));
262
    }
263
264
    /**
265
     * @param $id
266
     *
267
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
268
     *
269
     * @throws NotFoundHttpException
270
     *
271
     * @Route("/{id}/delete", requirements={"id" = "\d+"}, name="KunstmaanTranslatorBundle_settings_translations_delete")
272
     * @Method({"GET", "POST"})
273
     */
274
    public function deleteAction(Request $request, $id)
275
    {
276
        /* @var $em EntityManager */
277
        $em = $this->getDoctrine()->getManager();
278
279
        $indexUrl = $this->getAdminListConfigurator()->getIndexUrl();
280
        if ($request->isMethod('POST')) {
281
            $em->getRepository('KunstmaanTranslatorBundle:Translation')->removeTranslations($id);
282
        }
283
284
        return new RedirectResponse($this->generateUrl($indexUrl['path'], isset($indexUrl['params']) ? $indexUrl['params'] : []));
285
    }
286
287
    /**
288
     * @param $adminListConfigurator
289
     */
290
    public function setAdminListConfigurator($adminListConfigurator)
291
    {
292
        $this->adminListConfigurator = $adminListConfigurator;
293
    }
294
295
    /**
296
     * @return AbstractAdminListConfigurator
297
     */
298
    public function getAdminListConfigurator()
299
    {
300
        $locales = $this->container->getParameter('kuma_translator.managed_locales');
301
302
        if (!isset($this->adminListConfigurator)) {
303
            $this->adminListConfigurator = new TranslationAdminListConfigurator($this->getDoctrine()->getConnection(), $locales);
304
        }
305
306
        return $this->adminListConfigurator;
307
    }
308
309
    /**
310
     * @param Request $request
311
     *
312
     * @return JsonResponse|Response
313
     *
314
     * @Route("/inline-edit", name="KunstmaanTranslatorBundle_settings_translations_inline_edit")
315
     * @Method({"POST"})
316
     */
317
    public function inlineEditAction(Request $request)
318
    {
319
        $values = $request->request->all();
320
321
        $adminListConfigurator = $this->getAdminListConfigurator();
322
        if (!$adminListConfigurator->canEditInline($values)) {
323
            throw $this->createAccessDeniedException('Not allowed to edit this translation');
324
        }
325
326
        $id = isset($values['pk']) ? (int) $values['pk'] : 0;
327
        $em = $this->getDoctrine()->getManager();
328
        /**
329
         * @var TranslatorInterface
330
         */
331
        $translator = $this->container->get('translator');
332
333
        try {
334
            if ($id !== 0) {
335
                // Find existing translation
336
                $translation = $em->getRepository('KunstmaanTranslatorBundle:Translation')->find($id);
337
338
                if (is_null($translation)) {
339
                    return new Response($translator->trans('translator.translator.invalid_translation'), 500);
340
                }
341
            } else {
342
                // Create new translation
343
                $translation = new Translation();
344
                $translation->setDomain($values['domain']);
345
                $translation->setKeyword($values['keyword']);
346
                $translation->setLocale($values['locale']);
347
                $translation->setTranslationId($values['translationId']);
348
            }
349
            $translation->setText($values['value']);
350
            $em->persist($translation);
351
            $em->flush();
352
353
            return new JsonResponse([
354
                'success' => true,
355
                'uid' => $translation->getId(),
356
            ], 200);
357
        } catch (\Exception $e) {
358
            return new Response($translator->trans('translator.translator.fatal_error_occurred'), 500);
359
        }
360
    }
361
}
362