WidgetController   B
last analyzed

Complexity

Total Complexity 47

Size/Duplication

Total Lines 526
Duplicated Lines 8.37 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 47
lcom 1
cbo 12
dl 44
loc 526
rs 8.439
c 2
b 0
f 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
A apiWidgetsAction() 0 13 2
A showAction() 0 18 2
B newAction() 4 33 5
B createAction() 4 38 5
B editAction() 0 31 4
C stylizeAction() 0 103 12
A deleteAction() 17 17 2
A deleteBulkAction() 19 19 3
B unlinkAction() 0 28 4
B updatePositionAction() 0 27 3
A getAvailablePositionsAction() 0 9 1
B getJsonReponseFromException() 0 32 3
A getViewByReferenceId() 0 4 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like WidgetController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use WidgetController, and based on these observations, apply Extract Interface, too.

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\WidgetBundle\Form\WidgetStyleType;
18
use Victoire\Bundle\WidgetMapBundle\Exception\WidgetMapNotFoundException;
19
use Victoire\Bundle\WidgetMapBundle\Helper\WidgetMapHelper;
20
21
/**
22
 * Widget Controller.
23
 */
24
class WidgetController extends Controller
25
{
26
    use VictoireAlertifyControllerTrait;
27
28
    /**
29
     * Show a widget.
30
     *
31
     * @param Request $request
32
     * @param Widget  $widget
33
     * @param int     $viewReferenceId
34
     *
35
     * @Route("/victoire-dcms-public/widget/show/{id}/{viewReferenceId}", name="victoire_core_widget_show", options={"expose"=true})
36
     * @Template()
37
     * @ParamConverter("id", class="VictoireWidgetBundle:Widget")
38
     *
39
     * @throws Exception
40
     *
41
     * @return Response
42
     */
43
    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...
44
    {
45
        try {
46
            $view = $this->get('victoire_page.page_helper')->findPageByParameters(['id' => $viewReferenceId]);
47
            $this->get('victoire_widget_map.builder')->build($view);
48
            $this->get('victoire_core.current_view')->setCurrentView($view);
49
            $response = new JsonResponse([
50
                    'html'    => $this->get('victoire_widget.widget_renderer')->render($widget, $view),
51
                    'update'  => 'vic-widget-'.$widget->getId().'-container',
52
                    'success' => true,
53
                ]
54
            );
55
        } catch (Exception $ex) {
56
            $response = $this->getJsonReponseFromException($ex);
57
        }
58
59
        return $response;
60
    }
61
62
    /**
63
     * API widgets function.
64
     *
65
     * @param string $widgetIds       the widget ids to fetch in json
66
     * @param int    $viewReferenceId
67
     *
68
     * @Route("/victoire-dcms-public/api/widgets/{widgetIds}/{viewReferenceId}", name="victoire_core_widget_apiWidgets", options={"expose"=true})
69
     *
70
     * @return JsonResponse
71
     */
72
    public function apiWidgetsAction($widgetIds, $viewReferenceId)
73
    {
74
        $view = $this->get('victoire_page.page_helper')->findPageByParameters(['id' => $viewReferenceId]);
75
        $response = [];
76
        $widgets = $this->get('doctrine.orm.entity_manager')->getRepository('VictoireWidgetBundle:Widget')
77
            ->findBy(['id' => json_decode($widgetIds)]);
78
79
        foreach ($widgets as $widget) {
80
            $response[$widget->getId()] = $this->get('victoire_widget.widget_renderer')->render($widget, $view);
81
        }
82
83
        return new JsonResponse($response);
84
    }
85
86
    /**
87
     * New Widget.
88
     *
89
     * @param Request $request
90
     * @param string  $type          The type of the widget we edit
91
     * @param int     $viewReference The view reference where attach the widget
92
     * @param string  $slot          The slot where attach the widget
93
     * @param string  $quantum       The quantum letter used to avoid same form name
94
     *
95
     * @throws Exception
96
     *
97
     * @return JsonResponse
98
     * @Route("/victoire-dcms/widget/new/{type}/{viewReference}/{slot}/{quantum}", name="victoire_core_widget_new", defaults={"slot":null, "quantum":"a"}, options={"expose"=true})
99
     */
100
    public function newAction(Request $request, $type, $viewReference, $slot = null, $quantum = 'a')
101
    {
102
        try {
103
            $view = $this->getViewByReferenceId($viewReference);
104
105 View Code Duplication
            if (!$reference = $this->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...
106
                ->getOneReferenceByParameters(['id' => $viewReference])) {
107
                $reference = new ViewReference($viewReference);
108
            }
109
            $view->setReference($reference);
110
111
            $position = $request->query->has('position') ? $request->query->get('position') : null;
112
            $parentWidgetMap = $request->query->has('parentWidgetMap') ? $request->query->get('parentWidgetMap') : null;
113
            $widgetData = $this->get('victoire_widget.widget_manager')->newWidget(
114
                Widget::MODE_STATIC,
115
                $type,
116
                $slot,
117
                $view,
118
                $position,
119
                $parentWidgetMap,
120
                $quantum
121
            );
122
123
            $response = new JsonResponse([
124
                'success' => true,
125
                'html'    => $widgetData['html'],
126
            ]);
127
        } catch (Exception $ex) {
128
            $response = $this->getJsonReponseFromException($ex);
129
        }
130
131
        return $response;
132
    }
133
134
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$mode" missing
Loading history...
introduced by
Doc comment for parameter "$position" missing
Loading history...
introduced by
Doc comment for parameter "$parentWidgetMap" missing
Loading history...
introduced by
Doc comment for parameter "$quantum" missing
Loading history...
135
     * Create a widget.
136
     * This action needs 2 routes to handle the presence or not of "businessEntityId" and 'parentWidgetMap'
137
     * that are both integers but "businessEntityId" present only in !static mode.
138
     *
139
     * @param string $type             The type of the widget we edit
0 ignored issues
show
introduced by
Doc comment for parameter $type does not match actual variable name $mode
Loading history...
140
     * @param int    $viewReference    The view reference where attach the widget
0 ignored issues
show
introduced by
Doc comment for parameter $viewReference does not match actual variable name $type
Loading history...
141
     * @param string $slot             The slot where attach the widget
0 ignored issues
show
introduced by
Doc comment for parameter $slot does not match actual variable name $viewReference
Loading history...
142
     * @param string $businessEntityId The BusinessEntity::id (can be null if the submitted form is in static mode)
0 ignored issues
show
introduced by
Doc comment for parameter $businessEntityId does not match actual variable name $slot
Loading history...
143
     *
144
     * @return JsonResponse
145
     * @Route("/victoire-dcms/widget/create/static/{type}/{viewReference}/{slot}/{quantum}/{position}/{parentWidgetMap}", name="victoire_core_widget_create_static", defaults={"mode":"static", "slot":null, "businessEntityId":null, "position":null, "parentWidgetMap":null, "_format": "json", "quantum":"a"})
146
     * @Route("/victoire-dcms/widget/create/{mode}/{type}/{viewReference}/{slot}/{quantum}/{businessEntityId}/{position}/{parentWidgetMap}", name="victoire_core_widget_create", defaults={"slot":null, "businessEntityId":null, "position":null, "parentWidgetMap":null, "_format": "json", "quantum":"a"})
147
     * @Template()
148
     */
149
    public function createAction($mode, $type, $viewReference, $slot = null, $position = null, $parentWidgetMap = null, $businessEntityId = null, $quantum = null)
150
    {
151
        try {
152
            //services
153
            $view = $this->getViewByReferenceId($viewReference);
154
155
            $isNewPage = $view->getId() === null ? true : false;
156
157 View Code Duplication
            if (!$reference = $this->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...
158
                ->getOneReferenceByParameters(['id' => $viewReference])) {
159
                $reference = new ViewReference($viewReference);
160
            }
161
162
            $view->setReference($reference);
163
            $this->get('victoire_core.current_view')->setCurrentView($view);
164
165
            $this->congrat($this->get('translator')->trans('victoire.success.message', [], 'victoire'));
166
            $response = $this->get('widget_manager')->createWidget($mode, $type, $slot, $view, $businessEntityId, $position, $parentWidgetMap, $quantum);
167
168
            if ($isNewPage) {
169
                $response = new JsonResponse([
170
                    'success'  => true,
171
                    'redirect' => $this->generateUrl(
172
                        'victoire_core_page_show',
173
                        [
174
                            'url' => $reference->getUrl(),
175
                        ]
176
                    ),
177
                ]);
178
            } else {
179
                $response = new JsonResponse($response);
180
            }
181
        } catch (Exception $ex) {
182
            $response = $this->getJsonReponseFromException($ex);
183
        }
184
185
        return $response;
186
    }
187
188
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$mode" missing
Loading history...
introduced by
Doc comment for parameter "$quantum" missing
Loading history...
189
     * Edit a widget.
190
     *
191
     * @param Widget $widget           The widget to edit
192
     * @param int    $viewReference    The current view
193
     * @param string $businessEntityId The BusinessEntity::id (can be null if the submitted form is in static mode)
0 ignored issues
show
introduced by
Doc comment for parameter $businessEntityId does not match actual variable name $mode
Loading history...
194
     *
195
     * @return JsonResponse
196
     *
197
     * @Route("/victoire-dcms/widget/edit/{id}/{viewReference}/{mode}/{businessEntityId}", name="victoire_core_widget_edit", options={"expose"=true}, defaults={"quantum":"a", "mode": "static"})
198
     * @Route("/victoire-dcms/widget/update/{id}/{viewReference}/{mode}/{quantum}/{businessEntityId}", name="victoire_core_widget_update", defaults={"businessEntityId": null, "mode": "static"})
199
     * @Template()
200
     */
201
    public function editAction(Widget $widget, $viewReference, $mode = Widget::MODE_STATIC, $quantum = null, $businessEntityId = null)
202
    {
203
        $view = $this->getViewByReferenceId($viewReference);
204
        $this->get('victoire_widget_map.builder')->build($view);
205
        $this->get('victoire_widget_map.widget_data_warmer')->warm($this->getDoctrine()->getManager(), $view);
206
207
        if ($view instanceof BusinessTemplate && !$reference = $this->get('victoire_view_reference.repository')
208
            ->getOneReferenceByParameters(['viewId' => $view->getId()])) {
209
            $reference = new ViewReference($viewReference);
210
            $view->setReference($reference);
211
        }
212
        $this->get('victoire_core.current_view')->setCurrentView($view);
213
        try {
214
            $response = new JsonResponse(
215
                $this->get('widget_manager')->editWidget(
216
                    $this->get('request'),
217
                    $widget,
218
                    $view,
219
                    $quantum,
220
                    $businessEntityId,
221
                    $mode
222
                )
223
            );
224
225
            $this->congrat($this->get('translator')->trans('victoire.success.message', [], 'victoire'));
226
        } catch (Exception $ex) {
227
            $response = $this->getJsonReponseFromException($ex);
228
        }
229
230
        return $response;
231
    }
232
233
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
234
     * @TODO Simplify Action when reorganize with editAction
235
     *
236
     * Stylize a widget.
237
     *
238
     * @param Widget $widget        The widget to stylize
0 ignored issues
show
introduced by
Doc comment for parameter $widget does not match actual variable name $request
Loading history...
239
     * @param int    $viewReference The current view
0 ignored issues
show
introduced by
Doc comment for parameter $viewReference does not match actual variable name $widget
Loading history...
240
     *
241
     * @return JsonResponse
242
     *
243
     * @Route("/victoire-dcms/widget/stylize/{id}/{viewReference}", name="victoire_core_widget_stylize", options={"expose"=true})
244
     * @Template()
245
     */
246
    public function stylizeAction(Request $request, Widget $widget, $viewReference)
247
    {
248
        $view = $this->getViewByReferenceId($viewReference);
249
        $this->get('victoire_widget_map.builder')->build($view);
250
251
        try {
252
            $widgetView = WidgetMapHelper::getWidgetMapByWidgetAndView($widget, $view)->getView();
0 ignored issues
show
Bug introduced by
The method getView does only exist in Victoire\Bundle\WidgetMapBundle\Entity\WidgetMap, but not in Victoire\Bundle\WidgetMa...getMapNotFoundException.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
253
        } catch (WidgetMapNotFoundException $e) {
254
            return new JsonResponse([
255
                'success' => false,
256
                'message' => $e->getMessage(),
257
            ]);
258
        }
259
260
        if (!$view instanceof \Victoire\Bundle\TemplateBundle\Entity\Template) {
261
            $widgetViewReference = $this->get('victoire_view_reference.repository')
262
                ->getOneReferenceByParameters(['viewId' => $view->getId()]);
263
            $widgetView->setReference($widgetViewReference);
264
        }
265
266
        $this->get('victoire_core.current_view')->setCurrentView($view);
267
        try {
268
            if ($request->getMethod() === 'POST') {
269
                $form = $this->get('form.factory')->create(WidgetStyleType::class, $widget, [
270
                        'method' => 'POST',
271
                        'action' => $this->generateUrl(
272
                            'victoire_core_widget_stylize',
273
                            [
274
                                'id'            => $widget->getId(),
275
                                'viewReference' => $viewReference,
276
                            ]
277
                        ),
278
                    ]
279
                );
280
281
                $form->handleRequest($this->get('request'));
282
                if ($request->query->get('novalidate', false) === false && $form->isValid()) {
283
                    if ($form->has('deleteBackground') && $form->get('deleteBackground')->getData()) {
284
                        // @todo: dynamic responsive key
285
                        foreach (['', 'XS', 'SM', 'MD', 'LG'] as $key) {
286
                            $widget->{'deleteBackground'.$key}();
287
                        }
288
                    }
289
                    $this->get('doctrine.orm.entity_manager')->flush();
290
                    $params = [
291
                        'view'        => $view,
292
                        'quantum'     => $widget->getQuantum(),
293
                        'success'     => true,
294
                        'html'        => $this->get('victoire_widget.widget_renderer')->render($widget, $view),
295
                        'widgetId'    => $widget->getId(),
296
                        'viewCssHash' => $view->getCssHash(),
297
                    ];
298
                } else {
299
                    $template = ($request->query->get('novalidate', false) !== false) ? 'VictoireCoreBundle:Widget/Form/stylize:form.html.twig' : 'VictoireCoreBundle:Widget/Form:stylize.html.twig';
300
                    $params = [
301
                        'success' => !$form->isSubmitted(),
302
                        'html'    => $this->get('templating')->render(
303
                            $template,
304
                            [
305
                                'view'   => $view,
306
                                'form'   => $form->createView(),
307
                                'widget' => $widget,
308
                            ]
309
                        ),
310
                    ];
311
                }
312
            } else {
313
                $widgets = $widget->getWidgetMap()->getWidgets();
314
                $forms = [];
315
                foreach ($widgets as $_widget) {
316
                    $forms[] = $this->get('form.factory')->create(WidgetStyleType::class, $_widget, [
317
                            'method' => 'POST',
318
                            'action' => $this->generateUrl(
319
                                'victoire_core_widget_stylize',
320
                                [
321
                                    'id'            => $_widget->getId(),
322
                                    'viewReference' => $viewReference,
323
                                ]
324
                            ),
325
                        ]
326
                    )->createView();
327
                }
328
                $params = [
329
                    'html' => $this->get('templating')->render(
330
                        'VictoireCoreBundle:Widget/Form:stylize.html.twig',
331
                        [
332
                            'view'    => $view,
333
                            'forms'   => $forms,
334
                            'widget'  => $widget,
335
                            'widgets' => $widgets,
336
                            'quantum' => $widget->getQuantum(),
337
                        ]
338
                    ),
339
                ];
340
            }
341
342
            $response = new JsonResponse($params);
343
        } catch (Exception $ex) {
344
            $response = $this->getJsonReponseFromException($ex);
345
        }
346
347
        return $response;
348
    }
349
350
    /**
351
     * Delete a Widget.
352
     *
353
     * @param Widget $widget        The widget to delete
354
     * @param int    $viewReference The current view
355
     *
356
     * @return JsonResponse response
357
     * @Route("/victoire-dcms/widget/delete/{id}/{viewReference}", name="victoire_core_widget_delete", defaults={"_format": "json"})
358
     * @Template()
359
     */
360 View Code Duplication
    public function deleteAction(Widget $widget, $viewReference)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
361
    {
362
        $view = $this->getViewByReferenceId($viewReference);
363
        try {
364
            $widgetId = $widget->getId();
365
            $this->get('widget_manager')->deleteWidget($widget, $view);
366
367
            return new JsonResponse([
368
                    'success'  => true,
369
                    'message'  => $this->get('translator')->trans('victoire_widget.delete.success', [], 'victoire'),
370
                    'widgetId' => $widgetId,
371
                ]
372
            );
373
        } catch (Exception $ex) {
374
            return $this->getJsonReponseFromException($ex);
375
        }
376
    }
377
378
    /**
379
     * Delete a Widget quantum.
380
     *
381
     * @param Widget $widget        The widget to delete
382
     * @param int    $viewReference The current view
383
     *
384
     * @return JsonResponse response
385
     * @Route("/victoire-dcms/widget/delete/quantum/{id}/{viewReference}", name="victoire_core_widget_delete_bulk", defaults={"_format": "json"})
386
     * @Template()
387
     */
388 View Code Duplication
    public function deleteBulkAction(Widget $widget, $viewReference)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
389
    {
390
        $view = $this->getViewByReferenceId($viewReference);
391
        try {
392
            $widgets = $widget->getWidgetMap()->getWidgets();
393
394
            foreach ($widgets as $widget) {
395
                $this->get('widget_manager')->deleteWidget($widget, $view);
396
            }
397
398
            return new JsonResponse([
399
                    'success' => true,
400
                    'message' => $this->get('translator')->trans('victoire_widget.delete.success', [], 'victoire'),
401
                ]
402
            );
403
        } catch (Exception $ex) {
404
            return $this->getJsonReponseFromException($ex);
405
        }
406
    }
407
408
    /**
409
     * Unlink a Widget by id
410
     * -> used to unlink an invalid widget after a bad widget unplug.
411
     *
412
     * @param int $id            The widgetId to unlink
413
     * @param int $viewReference The current viewReference
414
     *
415
     * @return JsonResponse response
416
     * @Route("/victoire-dcms/widget/unlink/{id}/{viewReference}", name="victoire_core_widget_unlink", defaults={"_format": "json"}, options={"expose"=true})
417
     * @Template()
418
     */
419
    public function unlinkAction($id, $viewReference)
420
    {
421
        $view = $this->getViewByReferenceId($viewReference);
422
        try {
423
            $this->get('victoire_widget.widget_helper')->deleteById($id);
424
            $this->get('doctrine.orm.entity_manager')->flush();
425
426
            if ($view instanceof Template) {
427
                $redirect = $this->generateUrl('victoire_template_show', ['id' => $view->getId()]);
0 ignored issues
show
Bug introduced by
The method getId() 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...
428
            } elseif ($view instanceof BusinessTemplate) {
429
                $redirect = $this->generateUrl('victoire_business_template_show', ['id' => $view->getId()]);
430
            } else {
431
                $viewReference = $this->get('victoire_view_reference.repository')
432
                    ->getOneReferenceByParameters(['viewId' => $view->getId()]);
433
434
                $redirect = $this->generateUrl('victoire_core_page_show', [
435
                        'url' => $viewReference->getUrl(),
436
                    ]);
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 16 spaces, but found 20.
Loading history...
437
            }
438
439
            return new JsonResponse([
440
                    'success'  => true,
441
                    'redirect' => $redirect,
442
                ]);
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 12 spaces, but found 16.
Loading history...
443
        } catch (Exception $ex) {
444
            return $this->getJsonReponseFromException($ex);
445
        }
446
    }
447
448
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
449
     * Update widget positions accross the view. If moved widget is a Reference, ask to detach the view from template.
450
     *
451
     * @param int $viewReference The current viewReference
0 ignored issues
show
introduced by
Doc comment for parameter $viewReference does not match actual variable name $request
Loading history...
452
     *
453
     * @return JsonResponse
454
     * @Route("/victoire-dcms/widget/updatePosition/{viewReference}", name="victoire_core_widget_update_position", options={"expose"=true})
455
     */
456
    public function updatePositionAction(Request $request, $viewReference)
457
    {
458
        $view = $this->getViewByReferenceId($viewReference);
459
        try {
460
            //the sorted order for the widgets
461
            $sortedWidget = $request->get('sorted');
462
            $em = $this->get('doctrine.orm.entity_manager');
463
            if (!$view->getId()) {
464
                //This view does not have an id, so it's a non persisted BEP. To keep this new order, well have to persist it.
465
                $em->persist($view);
466
                $em->flush();
467
            }
468
            $this->get('victoire_widget_map.builder')->build($view);
469
            //recompute the order for the widgets
470
            $this->get('victoire_widget_map.manager')->move($view, $sortedWidget);
471
            $em->flush();
472
473
            $this->get('victoire_widget_map.builder')->build($view);
474
            $availablePositions = $this->get('victoire_widget_map.builder')->getAvailablePosition($view);
475
476
            $response = new JsonResponse(['success' => true, 'availablePositions' => $availablePositions]);
477
        } catch (Exception $ex) {
478
            $response = $this->getJsonReponseFromException($ex);
479
        }
480
481
        return $response;
482
    }
483
484
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
485
     * Update widget positions accross the view. If moved widget is a Reference, ask to detach the view from template.
486
     *
487
     * @param int $viewReference The current viewReference
0 ignored issues
show
introduced by
Doc comment for parameter $viewReference does not match actual variable name $request
Loading history...
488
     *
489
     * @return JsonResponse
490
     * @Route("/victoire-dcms/widget/get-available-positions/{viewReference}", name="victoire_core_widget_get_available_positions", options={"expose"=true})
491
     */
492
    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...
493
    {
494
        $view = $this->getViewByReferenceId($viewReference);
495
496
        $this->get('victoire_widget_map.builder')->build($view);
497
        $availablePositions = $this->get('victoire_widget_map.builder')->getAvailablePosition($view);
498
499
        return new JsonResponse($availablePositions);
500
    }
501
502
    /**
503
     * Get the json response by the exception and the current user.
504
     *
505
     * @param Exception $ex
506
     *
507
     * @return JsonResponse
508
     */
509
    protected function getJsonReponseFromException(Exception $ex)
510
    {
511
        //services
512
        $securityContext = $this->get('security.context');
513
        $logger = $this->get('logger');
514
515
        //can we see the debug
516
        $isDebugAllowed = $securityContext->isGranted('ROLE_VICTOIRE_PAGE_DEBUG') ? true : $this->get('kernel')->isDebug();
517
518
        //whatever is the exception, we log it
519
        $logger->error($ex->getMessage());
520
        $logger->error($ex->getTraceAsString());
521
522
        if ($isDebugAllowed) {
523
            throw $ex;
524
        } else {
525
            //translate the message
526
            $translator = $this->get('translator');
527
528
            //get the translated message
529
            $message = $translator->trans('error_occured', [], 'victoire');
530
531
            $response = new JsonResponse(
532
                [
533
                    'success' => false,
534
                    'message' => $message,
535
                ]
536
            );
537
        }
538
539
        return $response;
540
    }
541
542
    /**
543
     * @param int $referenceId
544
     */
545
    protected function getViewByReferenceId($referenceId)
546
    {
547
        return $this->get('victoire_page.page_helper')->findPageByParameters(['id' => $referenceId]);
548
    }
549
}
550