Passed
Push — master ( c9bd7c...617e81 )
by Dāvis
02:28
created

TranslationCRUDController::batchActionDownload()   B

Complexity

Conditions 6
Paths 1

Size

Total Lines 43
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 27
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 43
rs 8.439
1
<?php
2
3
namespace Sludio\HelperBundle\Lexik\Controller;
4
5
use Doctrine\DBAL\DBALException;
0 ignored issues
show
Bug introduced by
The type Doctrine\DBAL\DBALException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Sludio\HelperBundle\Lexik\Event\RemoveLocaleCacheEvent;
7
use Lexik\Bundle\TranslationBundle\Entity\TransUnit;
8
use Lexik\Bundle\TranslationBundle\Manager\TranslationInterface;
9
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
10
use Symfony\Component\HttpFoundation\Response;
11
use Sonata\AdminBundle\Controller\CRUDController;
12
use Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException;
13
use Symfony\Component\HttpFoundation\RedirectResponse;
14
use Symfony\Component\HttpFoundation\Request;
15
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
16
use Symfony\Component\HttpFoundation\StreamedResponse;
17
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
18
use Symfony\Component\Yaml\Dumper;
19
20
class TranslationCRUDController extends CRUDController
21
{
22
    /**
23
     * Edit action
24
     *
25
     * @param int|string|null $id
26
     *
27
     * @return Response|RedirectResponse
28
     * @throws NotFoundHttpException If the object does not exist
29
     * @throws NotFoundHttpException If the object does not exist
30
     * @throws AccessDeniedException If access is not granted
31
     * @throws AccessDeniedException If access is not granted
32
     */
33
    public function editAction($id = null, Request $request = null)
34
    {
35
        if (!$request) {
36
            $request = $this->getRequest();
37
        }
38
        if (!$request->isMethod('POST')) {
39
            return $this->redirect($this->admin->generateUrl('list'));
40
        }
41
42
        /* @var $transUnit \Lexik\Bundle\TranslationBundle\Model\TransUnit */
43
        $transUnit = $this->get('lexik_translation.translation_storage')->getTransUnitById($id);
44
        if (!$transUnit) {
45
            throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
46
        }
47
48
        if (false === $this->admin->isGranted('EDIT', $transUnit)) {
49
            return $this->renderJson([
50
                'message' => 'access denied',
51
            ], 403);
52
        }
53
54
        $this->admin->setSubject($transUnit);
55
56
        /* @var $transUnitManager \Lexik\Bundle\TranslationBundle\Manager\TransUnitManager */
57
        $transUnitManager = $this->get('lexik_translation.trans_unit.manager');
58
59
        $parameters = $this->getRequest()->request;
60
61
        $locale = $parameters->get('locale');
62
        $content = $parameters->get('value');
63
64
        if (!$locale) {
65
            return $this->renderJson([
66
                'message' => 'locale missing',
67
            ], 422);
68
        }
69
70
        /* @var $translation \Lexik\Bundle\TranslationBundle\Model\Translation */
71
        if ($parameters->get('pk')) {
72
            $translation = $transUnitManager->updateTranslation($transUnit, $locale, $content, true);
73
        } else {
74
            $translation = $transUnitManager->addTranslation($transUnit, $locale, $content, null, true);
75
        }
76
77
        if ($request->query->get('clear_cache')) {
78
            $this->get('translator')->removeLocalesCacheFiles([$locale]);
79
        }
80
81
        return $this->renderJson([
82
            'key' => $transUnit->getKey(),
83
            'domain' => $transUnit->getDomain(),
84
            'pk' => $translation->getId(),
0 ignored issues
show
Bug introduced by
The method getId() does not exist on Lexik\Bundle\TranslationBundle\Model\Translation. It seems like you code against a sub-type of Lexik\Bundle\TranslationBundle\Model\Translation such as Lexik\Bundle\TranslationBundle\Entity\Translation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

84
            'pk' => $translation->/** @scrutinizer ignore-call */ getId(),
Loading history...
85
            'locale' => $translation->getLocale(),
86
            'value' => $translation->getContent(),
87
        ]);
88
    }
89
90
    /**
91
     * @return RedirectResponse|Response
92
     */
93
    public function createTransUnitAction()
94
    {
95
        $request = $this->getRequest();
96
        $parameters = $this->getRequest()->request;
97
        if (!$request->isMethod('POST')) {
98
            return $this->renderJson([
99
                'message' => 'method not allowed',
100
            ], 403);
101
        }
102
        $admin = $this->admin;
103
        if (false === $admin->isGranted('EDIT')) {
104
            return $this->renderJson([
105
                'message' => 'access denied',
106
            ], 403);
107
        }
108
        $keyName = $parameters->get('key');
109
        $domainName = $parameters->get('domain');
110
        if (!$keyName || !$domainName) {
111
            return $this->renderJson([
112
                'message' => 'missing key or domain',
113
            ], 422);
114
        }
115
116
        /* @var $transUnitManager \Lexik\Bundle\TranslationBundle\Manager\TransUnitManager */
117
        $transUnitManager = $this->get('lexik_translation.trans_unit.manager');
118
        $transUnit = $transUnitManager->create($keyName, $domainName, true);
119
120
        return $this->editAction($transUnit->getId());
121
    }
122
123
    /**
124
     * @return RedirectResponse
125
     */
126
    public function clearCacheAction()
127
    {
128
        $this->get('event_dispatcher')
129
            ->dispatch(RemoveLocaleCacheEvent::PRE_REMOVE_LOCAL_CACHE, new RemoveLocaleCacheEvent($this->getManagedLocales()))
130
        ;
131
        $this->get('translator')->removeLocalesCacheFiles($this->getManagedLocales());
132
        $this->get('event_dispatcher')
133
            ->dispatch(RemoveLocaleCacheEvent::POST_REMOVE_LOCAL_CACHE, new RemoveLocaleCacheEvent($this->getManagedLocales()))
134
        ;
135
136
        /** @var $session Session */
137
        $session = $this->get('session');
138
        $session->getFlashBag()->set('sonata_flash_success', 'translations.cache_removed');
139
140
        return $this->redirect($this->admin->generateUrl('list'));
141
    }
142
143
    /**
144
     * Execute a batch download
145
     *
146
     * @param ProxyQueryInterface $query
147
     *
148
     * @return RedirectResponse
149
     */
150
    public function batchActionDownload(ProxyQueryInterface $queryProxy)
151
    {
152
        $flashType = 'success';
153
154
        $dumper = new Dumper();
155
        $dumper->setIndentation(4);
0 ignored issues
show
Deprecated Code introduced by
The function Symfony\Component\Yaml\Dumper::setIndentation() has been deprecated: since version 3.1, to be removed in 4.0. Pass the indentation to the constructor instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

155
        /** @scrutinizer ignore-deprecated */ $dumper->setIndentation(4);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
156
157
        $response = new StreamedResponse(function() use ($queryProxy, &$flashType, $dumper) {
158
            try {
159
                /**
160
                 * @var TransUnit $transUnit
161
                 */
162
                foreach ($queryProxy->getQuery()->iterate() as $pos => $object) {
163
                    foreach ($object as $transUnit) {
164
                        $chunkPrefix = $transUnit->getDomain().'__'.$transUnit->getKey().'__'.$transUnit->getId().'__';
165
                        $chunk = [];
166
                        /** @var TranslationInterface $translation */
167
                        foreach ($transUnit->getTranslations() as $translation) {
168
                            $chunk[$chunkPrefix.$translation->getLocale()] = $translation->getContent();
169
                        }
170
                        echo $dumper->dump($chunk, 2);
171
                        flush();
172
                    }
173
                }
174
            } catch (\PDOException $e) {
175
                $flashType = 'error';
176
                flush();
177
            } catch (DBALException $e) {
178
                $flashType = 'error';
179
                flush();
180
            }
181
        });
182
183
        $this->addFlash('sonata_flash_'.$flashType, 'translations.flash_batch_download_'.$flashType);
184
185
        $response->headers->set('Content-Type', 'text/x-yaml');
186
        $response->headers->set('Cache-Control', '');
187
        $response->headers->set('Transfer-Encoding', 'chunked');
188
        $response->headers->set('Last-Modified', gmdate('D, d M Y H:i:s'));
189
        $contentDisposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'translations.yml');
190
        $response->headers->set('Content-Disposition', $contentDisposition);
191
192
        return $response;
193
    }
194
195
    protected function getManagedLocales()
196
    {
197
        return $this->container->getParameter('lexik_translation.managed_locales');
198
    }
199
200
    public function __toString()
201
    {
202
        return 'sludio_helper.lexik.crud.controller';
203
    }
204
}