Completed
Pull Request — master (#338)
by Leny
06:17
created

WidgetController::updatePositionAction()   B

Complexity

Conditions 3
Paths 19

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 27
rs 8.8571
cc 3
eloc 17
nc 19
nop 2
1
<?php
2
3
namespace Victoire\Bundle\WidgetBundle\Controller;
4
5
use Exception;
6
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
7
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
8
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
9
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
10
use Symfony\Component\HttpFoundation\JsonResponse;
11
use Symfony\Component\HttpFoundation\Request;
12
use Symfony\Component\HttpFoundation\Response;
13
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessTemplate;
14
use Victoire\Bundle\CoreBundle\Controller\VictoireAlertifyControllerTrait;
15
use Victoire\Bundle\ViewReferenceBundle\ViewReference\ViewReference;
16
use Victoire\Bundle\WidgetBundle\Entity\Widget;
17
use Victoire\Bundle\WidgetMapBundle\Helper\WidgetMapHelper;
18
19
/**
20
 * Widget Controller.
21
 */
22
class WidgetController extends Controller
23
{
24
    use VictoireAlertifyControllerTrait;
25
26
    /**
27
     * Show a widget.
28
     *
29
     * @param Request $request
30
     * @param Widget  $widget
31
     * @param int     $viewReferenceId
32
     *
33
     * @Route("/victoire-dcms-public/widget/show/{id}/{viewReferenceId}", name="victoire_core_widget_show", options={"expose"=true})
34
     * @Template()
35
     * @ParamConverter("id", class="VictoireWidgetBundle:Widget")
36
     *
37
     * @throws Exception
38
     *
39
     * @return Response
40
     */
41
    public function showAction(Request $request, Widget $widget, $viewReferenceId)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
42
    {
43
        //the response is for the ajax.js from the AppVentus Ajax Bundle
44
        try {
45
            $view = $this->container->get('victoire_page.page_helper')->findPageByParameters(['id' => $viewReferenceId]);
46
            $this->container->get('victoire_core.current_view')->setCurrentView($view);
47
            $response = new JsonResponse([
48
                    'html'    => $this->get('victoire_widget.widget_renderer')->render($widget, $view),
49
                    'update'  => 'vic-widget-'.$widget->getId().'-container',
50
                    'success' => false,
51
                ]
52
            );
53
        } catch (Exception $ex) {
54
            $response = $this->getJsonReponseFromException($ex);
55
        }
56
57
        return $response;
58
    }
59
60
    /**
61
     * API widgets function.
62
     *
63
     * @param string $widgetIds       the widget ids to fetch in json
64
     * @param int    $viewReferenceId
65
     *
66
     * @Route("/victoire-dcms-public/api/widgets/{widgetIds}/{viewReferenceId}", name="victoire_core_widget_apiWidgets", options={"expose"=true})
67
     *
68
     * @return JsonResponse
69
     */
70
    public function apiWidgetsAction($widgetIds, $viewReferenceId)
71
    {
72
        $view = $this->container->get('victoire_page.page_helper')->findPageByParameters(['id' => $viewReferenceId]);
73
        $response = [];
74
        $widgets = $this->get('doctrine.orm.entity_manager')->getRepository('VictoireWidgetBundle:Widget')
75
            ->findBy(['id' => json_decode($widgetIds)]);
76
77
        foreach ($widgets as $widget) {
78
            $response[$widget->getId()] = $this->get('victoire_widget.widget_renderer')->render($widget, $view);
79
        }
80
81
        return new JsonResponse($response);
82
    }
83
84
    /**
85
     * New Widget.
86
     *
87
     * @param string $type          The type of the widget we edit
88
     * @param int    $viewReference The view reference where attach the widget
89
     * @param string $slot          The slot where attach the widget
90
     *
91
     * @return JsonResponse
92
     *
93
     * @Route("/victoire-dcms/widget/new/{type}/{viewReference}/{slot}/{position}/{parentWidgetMap}", name="victoire_core_widget_new", defaults={"slot":null, "position":null, "parentWidgetMap":null}, options={"expose"=true})
94
     * @Template()
95
     */
96
    public function newAction($type, $viewReference, $slot = null, $position = null, $parentWidgetMap = null)
97
    {
98
        try {
99
            $view = $this->getViewByReferenceId($viewReference);
100
101 View Code Duplication
            if (!$reference = $this->container->get('victoire_view_reference.repository')
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
102
                ->getOneReferenceByParameters(['id' => $viewReference])) {
103
                $reference = new ViewReference($viewReference);
104
            }
105
            $view->setReference($reference);
106
107
            $response = new JsonResponse(
108
                $this->get('victoire_widget.widget_manager')->newWidget(Widget::MODE_STATIC, $type, $slot, $view, $position, $parentWidgetMap)
109
            );
110
        } catch (Exception $ex) {
111
            $response = $this->getJsonReponseFromException($ex);
112
        }
113
114
        return $response;
115
    }
116
117
    /**
118
     * Create a widget.
119
     * This action needs 2 routes to handle the presence or not of "businessEntityId" and 'parentWidgetMap'
120
     * that are both integers but "businessEntityId" present only in !static mode.
121
     *
122
     * @param string $type             The type of the widget we edit
123
     * @param int    $viewReference    The view reference where attach the widget
124
     * @param string $slot             The slot where attach the widget
125
     * @param string $businessEntityId The BusinessEntity::id (can be null if the submitted form is in static mode)
126
     *
127
     * @return JsonResponse
128
     * @Route("/victoire-dcms/widget/create/static/{type}/{viewReference}/{slot}/{position}/{parentWidgetMap}", name="victoire_core_widget_create_static", defaults={"mode":"static", "slot":null, "businessEntityId":null, "position":null, "parentWidgetMap":null, "_format": "json"})
129
     * @Route("/victoire-dcms/widget/create/{mode}/{type}/{viewReference}/{slot}/{businessEntityId}/{position}/{parentWidgetMap}", name="victoire_core_widget_create", defaults={"slot":null, "businessEntityId":null, "position":null, "parentWidgetMap":null, "_format": "json"})
130
     * @Template()
131
     */
132
    public function createAction($mode, $type, $viewReference, $slot = null, $position = null, $parentWidgetMap = null, $businessEntityId = null)
133
    {
134
        try {
135
            //services
136
            $view = $this->getViewByReferenceId($viewReference);
137
138
            $isNewPage = $view->getId() === null ? true : false;
139
140 View Code Duplication
            if (!$reference = $this->container->get('victoire_view_reference.repository')
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
141
                ->getOneReferenceByParameters(['id' => $viewReference])) {
142
                $reference = new ViewReference($viewReference);
143
            }
144
145
            $view->setReference($reference);
146
            $this->get('victoire_core.current_view')->setCurrentView($view);
147
148
            $this->congrat($this->get('translator')->trans('victoire.success.message', [], 'victoire'));
149
            $response = $this->get('widget_manager')->createWidget($mode, $type, $slot, $view, $businessEntityId, $position, $parentWidgetMap);
150
151
            if ($isNewPage) {
152
                $response = new JsonResponse([
153
                    'success'  => true,
154
                    'redirect' => $this->generateUrl(
155
                        'victoire_core_page_show',
156
                        [
157
                            'url' => $reference->getUrl(),
158
                        ]
159
                    ),
160
                ]);
161
            } else {
162
                $response = new JsonResponse($response);
163
            }
164
        } catch (Exception $ex) {
165
            $response = $this->getJsonReponseFromException($ex);
166
        }
167
168
        return $response;
169
    }
170
171
    /**
172
     * Edit a widget.
173
     *
174
     * @param Widget $widget           The widget to edit
175
     * @param int    $viewReference    The current view
176
     * @param string $businessEntityId The BusinessEntity::id (can be null if the submitted form is in static mode)
177
     *
178
     * @return JsonResponse
179
     *
180
     * @Route("/victoire-dcms/widget/edit/{id}/{viewReference}/{mode}/{businessEntityId}", name="victoire_core_widget_edit", options={"expose"=true})
181
     * @Route("/victoire-dcms/widget/update/{id}/{viewReference}/{mode}/{businessEntityId}", name="victoire_core_widget_update", defaults={"businessEntityId": null})
182
     * @Template()
183
     */
184
    public function editAction(Widget $widget, $viewReference, $mode = Widget::MODE_STATIC, $businessEntityId = null)
185
    {
186
        $view = $this->getViewByReferenceId($viewReference);
187
        $this->get('victoire_widget_map.builder')->build($view, $this->get('doctrine.orm.entity_manager'));
188
        $widgetView = WidgetMapHelper::getWidgetMapByWidgetAndView($widget, $view)->getView();
189
        $this->get('victoire_widget_map.widget_data_warmer')->warm($this->getDoctrine()->getManager(), $view);
190
191
        if ($view instanceof BusinessTemplate && !$reference = $this->container->get('victoire_view_reference.repository')
192
            ->getOneReferenceByParameters(['viewId' => $view->getId()])) {
193
            $reference = new ViewReference($viewReference);
194
            $widgetView->setReference($reference);
195
        }
196
        $widget->setCurrentView($widgetView);
197
        $this->get('victoire_core.current_view')->setCurrentView($view);
198
        try {
199
            $response = new JsonResponse(
200
                $this->get('widget_manager')->editWidget(
201
                    $this->get('request'),
202
                    $widget,
203
                    $view,
204
                    $businessEntityId,
205
                    $mode
206
                )
207
            );
208
209
            $this->congrat($this->get('translator')->trans('victoire.success.message', [], 'victoire'));
210
        } catch (Exception $ex) {
211
            $response = $this->getJsonReponseFromException($ex);
212
        }
213
214
        return $response;
215
    }
216
217
    /**
218
     * Stylize a widget.
219
     *
220
     * @param Widget $widget        The widget to stylize
221
     * @param int    $viewReference The current view
222
     *
223
     * @return JsonResponse
224
     *
225
     * @Route("/victoire-dcms/widget/stylize/{id}/{viewReference}", name="victoire_core_widget_stylize", options={"expose"=true})
226
     * @Template()
227
     */
228
    public function stylizeAction(Request $request, Widget $widget, $viewReference)
229
    {
230
        $view = $this->getViewByReferenceId($viewReference);
231
        $this->get('victoire_widget_map.builder')->build($view, $this->get('doctrine.orm.entity_manager'));
232
        $widgetView = WidgetMapHelper::getWidgetMapByWidgetAndView($widget, $view)->getView();
233
234
        $widgetViewReference = $this->container->get('victoire_view_reference.repository')
235
            ->getOneReferenceByParameters(['viewId' => $view->getId()]);
236
237
        $widgetView->setReference($widgetViewReference);
238
        $this->get('victoire_core.current_view')->setCurrentView($view);
239
        try {
240
            $form = $this->container->get('form.factory')->create('victoire_widget_style_type', $widget, [
241
                    'method' => 'POST',
242
                    'action' => $this->generateUrl(
243
                        'victoire_core_widget_stylize',
244
                        [
245
                            'id'            => $widget->getId(),
246
                            'viewReference' => $viewReference,
247
                        ]
248
                    ),
249
                ]
250
            );
251
            $form->handleRequest($this->get('request'));
252
253
            if ($request->query->get('novalidate', false) === false && $form->isValid()) {
254
                if ($form->has('deleteBackground') && $form->get('deleteBackground')->getData()) {
255
                    // @todo: dynamic responsive key
256
                    foreach (['', 'XS', 'SM', 'MD', 'LG'] as $key) {
257
                        $widget->{'deleteBackground'.$key}();
258
                    }
259
                }
260
                $this->get('doctrine.orm.entity_manager')->flush();
261
                $params = [
262
                    'view'        => $view,
263
                    'success'     => true,
264
                    'html'        => $this->get('victoire_widget.widget_renderer')->render($widget, $view),
265
                    'widgetId'    => $widget->getId(),
266
                    'viewCssHash' => $view->getCssHash(),
267
                ];
268
            } else {
269
                $template = ($request->query->get('novalidate', false) !== false) ? 'VictoireCoreBundle:Widget/Form/stylize:form.html.twig' : 'VictoireCoreBundle:Widget/Form:stylize.html.twig';
270
                $params = [
271
                    'success'  => false,
272
                    'html'     => $this->get('victoire_core.template_mapper')->render(
273
                        $template,
274
                        [
275
                            'view'   => $view,
276
                            'form'   => $form->createView(),
277
                            'widget' => $widget,
278
                        ]
279
                    ),
280
                ];
281
            }
282
            $response = new JsonResponse($params);
283
        } catch (Exception $ex) {
284
            $response = $this->getJsonReponseFromException($ex);
285
        }
286
287
        return $response;
288
    }
289
290
    /**
291
     * Delete a Widget.
292
     *
293
     * @param Widget $widget        The widget to delete
294
     * @param int    $viewReference The current view
295
     *
296
     * @return JsonResponse response
297
     * @Route("/victoire-dcms/widget/delete/{id}/{viewReference}", name="victoire_core_widget_delete", defaults={"_format": "json"})
298
     * @Template()
299
     */
300
    public function deleteAction(Widget $widget, $viewReference)
301
    {
302
        $view = $this->getViewByReferenceId($viewReference);
303
        try {
304
            $widgetId = $widget->getId();
305
            $this->get('widget_manager')->deleteWidget($widget, $view);
306
307
            return new JsonResponse([
308
                    'success'  => true,
309
                    'message'  => $this->get('translator')->trans('victoire_widget.delete.success', [], 'victoire'),
310
                    'widgetId' => $widgetId,
311
                ]
312
            );
313
        } catch (Exception $ex) {
314
            return $this->getJsonReponseFromException($ex);
315
        }
316
    }
317
318
    /**
319
     * Unlink a Widget by id
320
     * -> used to unlink an invalid widget after a bad widget unplug.
321
     *
322
     * @param int $id            The widgetId to unlink
323
     * @param int $viewReference The current viewReference
324
     *
325
     * @return JsonResponse response
326
     * @Route("/victoire-dcms/widget/unlink/{id}/{viewReference}", name="victoire_core_widget_unlink", defaults={"_format": "json"}, options={"expose"=true})
327
     * @Template()
328
     */
329
    public function unlinkAction($id, $viewReference)
330
    {
331
        $view = $this->getViewByReferenceId($viewReference);
332
        try {
333
            $this->get('victoire_widget.widget_helper')->deleteById($id);
334
            $this->get('doctrine.orm.entity_manager')->flush();
335
336
            if ($view instanceof Template) {
337
                $redirect = $this->generateUrl('victoire_template_show', ['slug' => $view->getSlug()]);
0 ignored issues
show
Bug introduced by
The method getSlug() does not seem to exist on object<Sensio\Bundle\Fra...Configuration\Template>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
338
            } elseif ($view instanceof BusinessTemplate) {
339
                $redirect = $this->generateUrl('victoire_business_template_show', ['id' => $view->getId()]);
340
            } else {
341
                $viewReference = $this->container->get('victoire_view_reference.repository')
342
                    ->getOneReferenceByParameters(['viewId' => $view->getId()]);
343
344
                $redirect = $this->generateUrl('victoire_core_page_show', [
345
                        'url' => $viewReference->getUrl(),
346
                    ]);
347
            }
348
349
            return new JsonResponse([
350
                    'success'  => true,
351
                    'redirect' => $redirect,
352
                ]);
353
        } catch (Exception $ex) {
354
            return $this->getJsonReponseFromException($ex);
355
        }
356
    }
357
358
    /**
359
     * Update widget positions accross the view. If moved widget is a Reference, ask to detach the view from template.
360
     *
361
     * @param int $viewReference The current viewReference
362
     *
363
     * @return JsonResponse
364
     * @Route("/victoire-dcms/widget/updatePosition/{viewReference}", name="victoire_core_widget_update_position", options={"expose"=true})
365
     */
366
    public function updatePositionAction(Request $request, $viewReference)
367
    {
368
        $view = $this->getViewByReferenceId($viewReference);
369
        try {
370
            //the sorted order for the widgets
371
            $sortedWidget = $request->get('sorted');
372
            $em = $this->get('doctrine.orm.entity_manager');
373
            if (!$view->getId()) {
374
                //This view does not have an id, so it's a non persisted BEP. To keep this new order, well have to persist it.
375
                $em->persist($view);
376
                $em->flush();
377
            }
378
            $this->get('victoire_widget_map.builder')->build($view);
379
            //recompute the order for the widgets
380
            $this->get('victoire_widget_map.manager')->move($view, $sortedWidget);
381
            $em->flush();
382
383
            $this->get('victoire_widget_map.builder')->build($view);
384
            $availablePositions = $this->get('victoire_widget_map.builder')->getAvailablePosition($view);
385
386
            $response = new JsonResponse(['success' => true, 'availablePositions' => $availablePositions]);
387
        } catch (Exception $ex) {
388
            $response = $this->getJsonReponseFromException($ex);
389
        }
390
391
        return $response;
392
    }
393
394
    /**
395
     * Update widget positions accross the view. If moved widget is a Reference, ask to detach the view from template.
396
     *
397
     * @param int $viewReference The current viewReference
398
     *
399
     * @return JsonResponse
400
     * @Route("/victoire-dcms/widget/get-available-positions/{viewReference}", name="victoire_core_widget_get_available_positions", options={"expose"=true})
401
     */
402
    public function getAvailablePositionsAction(Request $request, $viewReference)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
403
    {
404
        $view = $this->getViewByReferenceId($viewReference);
405
406
        $this->get('victoire_widget_map.builder')->build($view);
407
        $availablePositions = $this->get('victoire_widget_map.builder')->getAvailablePosition($view);
408
409
        return new JsonResponse($availablePositions);
410
    }
411
412
    /**
413
     * Get the json response by the exception and the current user.
414
     *
415
     * @param Exception $ex
416
     *
417
     * @return JsonResponse
418
     */
419
    protected function getJsonReponseFromException(Exception $ex)
420
    {
421
        //services
422
        $securityContext = $this->get('security.context');
423
        $logger = $this->get('logger');
424
425
        //can we see the debug
426
        $isDebugAllowed = $securityContext->isGranted('ROLE_VICTOIRE_PAGE_DEBUG');
427
428
        //whatever is the exception, we log it
429
        $logger->error($ex->getMessage());
430
        $logger->error($ex->getTraceAsString());
431
432
        if ($isDebugAllowed) {
433
            throw $ex;
434
        } else {
435
            //translate the message
436
            $translator = $this->get('translator');
437
438
            //get the translated message
439
            $message = $translator->trans('error_occured', [], 'victoire');
440
441
            $response = new JsonResponse(
442
                [
443
                    'success' => false,
444
                    'message' => $message,
445
                ]
446
            );
447
        }
448
449
        return $response;
450
    }
451
452
    /**
453
     * @param int $referenceId
454
     */
455
    protected function getViewByReferenceId($referenceId)
456
    {
457
        return $this->get('victoire_page.page_helper')->findPageByParameters(['id' => $referenceId]);
458
    }
459
}
460