Completed
Pull Request — master (#325)
by Paul
08:12 queued 49s
created

WidgetController::newAction()   B

Complexity

Conditions 3
Paths 15

Size

Total Lines 32
Code Lines 20

Duplication

Lines 4
Ratio 12.5 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 4
loc 32
rs 8.8571
cc 3
eloc 20
nc 15
nop 5
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\ViewReferenceBundle\ViewReference\ViewReference;
15
use Victoire\Bundle\WidgetBundle\Entity\Widget;
16
17
/**
18
 * Widget Controller.
19
 */
20
class WidgetController extends Controller
21
{
22
    /**
23
     * Show a widget.
24
     *
25
     * @param Request $request
26
     * @param Widget  $widget
27
     * @param int     $viewReferenceId
28
     *
29
     * @Route("/victoire-dcms-public/widget/show/{id}/{viewReferenceId}", name="victoire_core_widget_show", options={"expose"=true})
30
     * @Template()
31
     * @ParamConverter("id", class="VictoireWidgetBundle:Widget")
32
     *
33
     * @throws Exception
34
     *
35
     * @return Response
36
     */
37
    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...
38
    {
39
        //the response is for the ajax.js from the AppVentus Ajax Bundle
40
        try {
41
            $view = $this->container->get('victoire_page.page_helper')->findPageByParameters(['id' => $viewReferenceId]);
42
            $this->container->get('victoire_core.current_view')->setCurrentView($view);
43
            $response = new JsonResponse([
44
                    'html'    => $this->get('victoire_widget.widget_renderer')->render($widget, $view),
45
                    'update'  => 'vic-widget-'.$widget->getId().'-container',
46
                    'success' => false,
47
                ]
48
            );
49
        } catch (Exception $ex) {
50
            $response = $this->getJsonReponseFromException($ex);
51
        }
52
53
        return $response;
54
    }
55
56
    /**
57
     * API widgets function.
58
     *
59
     * @param string $widgetIds       the widget ids to fetch in json
60
     * @param int    $viewReferenceId
61
     *
62
     * @Route("/victoire-dcms-public/api/widgets/{widgetIds}/{viewReferenceId}", name="victoire_core_widget_apiWidgets", options={"expose"=true})
63
     *
64
     * @return JsonResponse
65
     */
66
    public function apiWidgetsAction($widgetIds, $viewReferenceId)
67
    {
68
        $view = $this->container->get('victoire_page.page_helper')->findPageByParameters(['id' => $viewReferenceId]);
69
        $response = [];
70
        $widgets = $this->get('doctrine.orm.entity_manager')->getRepository('VictoireWidgetBundle:Widget')
71
            ->findBy(['id' => json_decode($widgetIds)]);
72
73
        foreach ($widgets as $widget) {
74
            $response[$widget->getId()] = $this->get('victoire_widget.widget_renderer')->render($widget, $view);
75
        }
76
77
        return new JsonResponse($response);
78
    }
79
80
    /**
81
     * New Widget.
82
     *
83
     * @param string $type              The type of the widget we edit
84
     * @param int    $viewReference     The view reference where attach the widget
85
     * @param string $slot              The slot where attach the widget
86
     * @param int    $positionReference The positionReference in the widgetMap
0 ignored issues
show
Documentation introduced by
There is no parameter named $positionReference. Did you maybe mean $position?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
87
     *
88
     * @return JsonResponse
89
     *
90
     * @Route("/victoire-dcms/widget/new/{type}/{viewReference}/{slot}/{position}/{widgetMapReference}", name="victoire_core_widget_new", defaults={"slot":null, "position":null, "widgetMapReference":null}, options={"expose"=true})
91
     * @Template()
92
     */
93
    public function newAction($type, $viewReference, $slot = null, $position = null, $widgetMapReference = null)
94
    {
95
        try {
96
            $view = $this->getViewByReferenceId($viewReference);
97
98 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...
99
                ->getOneReferenceByParameters(['id' => $viewReference])) {
100
                $reference = new ViewReference($viewReference);
101
            }
102
            $view->setReference($reference);
103
104
            $widget = $this->get('victoire_widget.widget_helper')->newWidgetInstance($type, $view, $slot, Widget::MODE_STATIC);
105
            $classes = $this->get('victoire_business_entity.cache_reader')->getBusinessClassesForWidget($widget);
106
            $forms = $this->get('victoire_widget.widget_form_builder')->renderNewWidgetForms($slot, $view, $widget, $classes, $position, $widgetMapReference);
107
108
            $response = new JsonResponse([
109
                    'html' => $this->get('victoire_templating')->render(
110
                        'VictoireCoreBundle:Widget:Form/new.html.twig',
111
                        [
112
                            'view'    => $view,
113
                            'classes' => $classes,
114
                            'widget'  => $widget,
115
                            'forms'   => $forms,
116
                        ]
117
                    ),
118
                ]);
119
        } catch (Exception $ex) {
120
            $response = $this->getJsonReponseFromException($ex);
121
        }
122
123
        return $response;
124
    }
125
126
    /**
127
     * Create a widget.
128
     *
129
     * @param string $type              The type of the widget we edit
130
     * @param int    $viewReference     The view reference where attach the widget
131
     * @param string $slot              The slot where attach the widget
132
     * @param int    $positionReference Position of the widget
0 ignored issues
show
Documentation introduced by
There is no parameter named $positionReference. Did you maybe mean $position?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
133
     * @param string $businessEntityId  The BusinessEntity::id (can be null if the submitted form is in static mode)
134
     *
135
     * @return JsonResponse
136
     * @Route("/victoire-dcms/widget/create/static/{type}/{viewReference}/{slot}/{position}/{widgetMapReference}", name="victoire_core_widget_create_static", defaults={"mode":"static", "slot":null, "businessEntityId":null, "position":null, "widgetMapReference":null, "_format": "json"})
137
     * @Route("/victoire-dcms/widget/create/{mode}/{type}/{viewReference}/{slot}/{businessEntityId}/{position}/{widgetMapReference}", name="victoire_core_widget_create", defaults={"slot":null, "businessEntityId":null, "position":null, "widgetMapReference":null, "_format": "json"})
138
     * @Template()
139
     */
140
    public function createAction($mode, $type, $viewReference, $slot = null, $position = null, $widgetMapReference = null, $businessEntityId = null)
141
    {
142
        try {
143
            //services
144
            $view = $this->getViewByReferenceId($viewReference);
145
146
            $isNewPage = $view->getId() === null ? true : false;
147
148 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...
149
                ->getOneReferenceByParameters(['id' => $viewReference])) {
150
                $reference = new ViewReference($viewReference);
151
            }
152
153
            $view->setReference($reference);
154
            $this->get('victoire_core.current_view')->setCurrentView($view);
155
156
            $response = $this->get('widget_manager')->createWidget($mode, $type, $slot, $view, $businessEntityId, $position, $widgetMapReference);
157
158
            if ($isNewPage) {
159
                $response = new JsonResponse([
160
                    'success'  => true,
161
                    'redirect' => $this->generateUrl(
162
                        'victoire_core_page_show',
163
                        [
164
                            'url' => $reference->getUrl(),
165
                        ]
166
                    ),
167
                ]);
168
            } else {
169
                $response = new JsonResponse($response);
170
            }
171
        } catch (Exception $ex) {
172
            $response = $this->getJsonReponseFromException($ex);
173
        }
174
175
        return $response;
176
    }
177
178
    /**
179
     * Edit a widget.
180
     *
181
     * @param Widget $widget           The widget to edit
182
     * @param int    $viewReference    The current view
183
     * @param string $businessEntityId The BusinessEntity::id (can be null if the submitted form is in static mode)
184
     *
185
     * @return JsonResponse
186
     *
187
     * @Route("/victoire-dcms/widget/edit/{id}/{viewReference}/{mode}/{businessEntityId}", name="victoire_core_widget_edit", options={"expose"=true})
188
     * @Route("/victoire-dcms/widget/update/{id}/{viewReference}/{mode}/{businessEntityId}", name="victoire_core_widget_update", defaults={"businessEntityId": null})
189
     * @Template()
190
     */
191
    public function editAction(Widget $widget, $viewReference, $mode = Widget::MODE_STATIC, $businessEntityId = null)
192
    {
193
        $view = $this->getViewByReferenceId($viewReference);
194
        $this->get('victoire_widget_map.builder')->build($view, $this->get('doctrine.orm.entity_manager'));
195
        $widgetView = $view->getWidgetMapByWidget($widget)->getView();
196
        $this->get('victoire_widget_map.widget_data_warmer')->warm($this->getDoctrine()->getManager(), $view);
197
198
        if ($view instanceof BusinessTemplate && !$reference = $this->container->get('victoire_view_reference.repository')
199
            ->getOneReferenceByParameters(['viewId' => $view->getId()])) {
200
            $reference = new ViewReference($viewReference);
201
            $widgetView->setReference($reference);
202
        }
203
        $widget->setCurrentView($widgetView);
204
        $this->get('victoire_core.current_view')->setCurrentView($view);
205
        try {
206
            $response = new JsonResponse(
207
                $this->get('widget_manager')->editWidget(
208
                    $this->get('request'),
209
                    $widget,
210
                    $view,
211
                    $businessEntityId,
212
                    $mode
213
                )
214
            );
215
        } catch (Exception $ex) {
216
            $response = $this->getJsonReponseFromException($ex);
217
        }
218
219
        return $response;
220
    }
221
222
    /**
223
     * Stylize a widget.
224
     *
225
     * @param Widget $widget        The widget to stylize
226
     * @param int    $viewReference The current view
227
     *
228
     * @return JsonResponse
229
     *
230
     * @Route("/victoire-dcms/widget/stylize/{id}/{viewReference}", name="victoire_core_widget_stylize", options={"expose"=true})
231
     * @Template()
232
     */
233
    public function stylizeAction(Request $request, Widget $widget, $viewReference)
234
    {
235
        $view = $this->getViewByReferenceId($viewReference);
236
        $widgetView = $widget->getView();
0 ignored issues
show
Deprecated Code introduced by
The method Victoire\Bundle\WidgetBu...ntity\Widget::getView() has been deprecated with message: Get view.

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

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

Loading history...
237
238
        $widgetViewReference = $this->container->get('victoire_view_reference.repository')
239
            ->getOneReferenceByParameters(['viewId' => $view->getId()]);
240
241
        $widgetView->setReference($widgetViewReference);
0 ignored issues
show
Bug introduced by
The method setReference cannot be called on $widgetView (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
242
        $this->get('victoire_core.current_view')->setCurrentView($view);
243
        try {
244
            $form = $this->container->get('form.factory')->create('victoire_widget_style_type', $widget, [
245
                    'method' => 'POST',
246
                    'action' => $this->generateUrl(
247
                        'victoire_core_widget_stylize',
248
                        [
249
                            'id'            => $widget->getId(),
250
                            'viewReference' => $viewReference,
251
                        ]
252
                    ),
253
                ]
254
            );
255
            $form->handleRequest($this->get('request'));
256
257
            if ($request->query->get('novalidate', false) === false && $form->isValid()) {
258
                if ($form->has('deleteBackground') && $form->get('deleteBackground')->getData()) {
259
                    // @todo: dynamic responsive key
260
                    foreach (['', 'XS', 'SM', 'MD', 'LG'] as $key) {
261
                        $widget->{'deleteBackground'.$key}();
262
                    }
263
                }
264
                $this->get('doctrine.orm.entity_manager')->flush();
265
                $params = [
266
                    'view'        => $view,
267
                    'success'     => true,
268
                    'html'        => $this->get('victoire_widget.widget_renderer')->render($widget, $view),
269
                    'widgetId'    => $widget->getId(),
270
                    'viewCssHash' => $view->getCssHash(),
271
                ];
272
            } else {
273
                $template = ($request->query->get('novalidate', false) !== false) ? 'VictoireCoreBundle:Widget/Form/stylize:form.html.twig' : 'VictoireCoreBundle:Widget/Form:stylize.html.twig';
274
                $params = [
275
                    'success'  => false,
276
                    'html'     => $this->get('victoire_core.template_mapper')->render(
277
                        $template,
278
                        [
279
                            'view'   => $view,
280
                            'form'   => $form->createView(),
281
                            'widget' => $widget,
282
                        ]
283
                    ),
284
                ];
285
            }
286
            $response = new JsonResponse($params);
287
        } catch (Exception $ex) {
288
            $response = $this->getJsonReponseFromException($ex);
289
        }
290
291
        return $response;
292
    }
293
294
    /**
295
     * Delete a Widget.
296
     *
297
     * @param Widget $widget        The widget to delete
298
     * @param int    $viewReference The current view
299
     *
300
     * @return JsonResponse response
301
     * @Route("/victoire-dcms/widget/delete/{id}/{viewReference}", name="victoire_core_widget_delete", defaults={"_format": "json"})
302
     * @Template()
303
     */
304
    public function deleteAction(Widget $widget, $viewReference)
305
    {
306
        $view = $this->getViewByReferenceId($viewReference);
307
        try {
308
            $widgetId = $widget->getId();
309
            $this->get('widget_manager')->deleteWidget($widget, $view);
310
311
            return new JsonResponse([
312
                    'success'  => true,
313
                    'message'  => $this->get('translator')->trans('victoire_widget.delete.success', [], 'victoire'),
314
                    'widgetId' => $widgetId,
315
                ]
316
            );
317
        } catch (Exception $ex) {
318
            return $this->getJsonReponseFromException($ex);
319
        }
320
    }
321
322
    /**
323
     * Unlink a Widget by id
324
     * -> used to unlink an invalid widget after a bad widget unplug.
325
     *
326
     * @param int $id            The widgetId to unlink
327
     * @param int $viewReference The current viewReference
328
     *
329
     * @return JsonResponse response
330
     * @Route("/victoire-dcms/widget/unlink/{id}/{viewReference}", name="victoire_core_widget_unlink", defaults={"_format": "json"}, options={"expose"=true})
331
     * @Template()
332
     */
333
    public function unlinkAction($id, $viewReference)
334
    {
335
        $view = $this->getViewByReferenceId($viewReference);
336
        try {
337
            $this->get('victoire_widget.widget_helper')->deleteById($id);
338
            $this->get('doctrine.orm.entity_manager')->flush();
339
340
            if ($view instanceof Template) {
341
                $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...
342
            } elseif ($view instanceof BusinessTemplate) {
343
                $redirect = $this->generateUrl('victoire_business_template_show', ['id' => $view->getId()]);
344
            } else {
345
                $viewReference = $this->container->get('victoire_view_reference.repository')
346
                    ->getOneReferenceByParameters(['viewId' => $view->getId()]);
347
348
                $redirect = $this->generateUrl('victoire_core_page_show', [
349
                        'url' => $viewReference->getUrl(),
350
                    ]);
351
            }
352
353
            return new JsonResponse([
354
                    'success'  => true,
355
                    'redirect' => $redirect,
356
                ]);
357
        } catch (Exception $ex) {
358
            return $this->getJsonReponseFromException($ex);
359
        }
360
    }
361
362
    /**
363
     * Update widget positions accross the view. If moved widget is a Reference, ask to detach the view from template.
364
     *
365
     * @param int $viewReference The current viewReference
366
     *
367
     * @return JsonResponse
368
     * @Route("/victoire-dcms/widget/updatePosition/{viewReference}", name="victoire_core_widget_update_position", options={"expose"=true})
369
     */
370
    public function updatePositionAction(Request $request, $viewReference)
371
    {
372
        $view = $this->getViewByReferenceId($viewReference);
373
        try {
374
            //the sorted order for the widgets
375
            $sortedWidget = $request->get('sorted');
376
            $em = $this->get('doctrine.orm.entity_manager');
377
            if (!$view->getId()) {
378
                //This view does not have an id, so it's a non persisted BEP. To keep this new order, well have to persist it.
379
                $em->persist($view);
380
                $em->flush();
381
            }
382
            $this->get('victoire_widget_map.builder')->build($view);
383
            //recompute the order for the widgets
384
            $this->get('victoire_widget_map.manager')->move($view, $sortedWidget);
385
            $em->flush();
386
387
            $this->get('victoire_widget_map.builder')->build($view);
388
            $availablePositions = $this->get('victoire_widget_map.builder')->getAvailablePosition($view);
389
390
            $response = new JsonResponse(['success' => true, 'availablePositions' => $availablePositions]);
391
        } catch (Exception $ex) {
392
            $response = $this->getJsonReponseFromException($ex);
393
        }
394
395
        return $response;
396
    }
397
398
    /**
399
     * Update widget positions accross the view. If moved widget is a Reference, ask to detach the view from template.
400
     *
401
     * @param int $viewReference The current viewReference
402
     *
403
     * @return JsonResponse
404
     * @Route("/victoire-dcms/widget/get-available-positions/{viewReference}", name="victoire_core_widget_get_available_positions", options={"expose"=true})
405
     */
406
    public function getAvailablePositions(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...
407
    {
408
        $view = $this->getViewByReferenceId($viewReference);
409
410
        $this->get('victoire_widget_map.builder')->build($view);
411
        $availablePositions = $this->get('victoire_widget_map.builder')->getAvailablePosition($view);
412
413
        return new JsonResponse($availablePositions);
414
    }
415
416
    /**
417
     * Get the json response by the exception and the current user.
418
     *
419
     * @param Exception $ex
420
     *
421
     * @return JsonResponse
422
     */
423
    protected function getJsonReponseFromException(Exception $ex)
424
    {
425
        //services
426
        $securityContext = $this->get('security.context');
427
        $logger = $this->get('logger');
428
429
        //can we see the debug
430
        $isDebugAllowed = $securityContext->isGranted('ROLE_VICTOIRE_PAGE_DEBUG');
431
432
        //whatever is the exception, we log it
433
        $logger->error($ex->getMessage());
434
        $logger->error($ex->getTraceAsString());
435
436
        if ($isDebugAllowed) {
437
            throw $ex;
438
        } else {
439
            //translate the message
440
            $translator = $this->get('translator');
441
442
            //get the translated message
443
            $message = $translator->trans('error_occured', [], 'victoire');
444
445
            $response = new JsonResponse(
446
                [
447
                    'success' => false,
448
                    'message' => $message,
449
                ]
450
            );
451
        }
452
453
        return $response;
454
    }
455
456
    /**
457
     * @param int $referenceId
458
     */
459
    protected function getViewByReferenceId($referenceId)
460
    {
461
        return $this->get('victoire_page.page_helper')->findPageByParameters(['id' => $referenceId]);
462
    }
463
}
464