Completed
Pull Request — master (#325)
by Paul
08:40
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
     *
87
     * @return JsonResponse
88
     *
89
     * @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})
90
     * @Template()
91
     */
92
    public function newAction($type, $viewReference, $slot = null, $position = null, $widgetMapReference = null)
93
    {
94
        try {
95
            $view = $this->getViewByReferenceId($viewReference);
96
97 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...
98
                ->getOneReferenceByParameters(['id' => $viewReference])) {
99
                $reference = new ViewReference($viewReference);
100
            }
101
            $view->setReference($reference);
102
103
            $widget = $this->get('victoire_widget.widget_helper')->newWidgetInstance($type, $view, $slot, Widget::MODE_STATIC);
104
            $classes = $this->get('victoire_business_entity.cache_reader')->getBusinessClassesForWidget($widget);
105
            $forms = $this->get('victoire_widget.widget_form_builder')->renderNewWidgetForms($slot, $view, $widget, $classes, $position, $widgetMapReference);
106
107
            $response = new JsonResponse([
108
                    'html' => $this->get('victoire_templating')->render(
109
                        'VictoireCoreBundle:Widget:Form/new.html.twig',
110
                        [
111
                            'view'    => $view,
112
                            'classes' => $classes,
113
                            'widget'  => $widget,
114
                            'forms'   => $forms,
115
                        ]
116
                    ),
117
                ]);
118
        } catch (Exception $ex) {
119
            $response = $this->getJsonReponseFromException($ex);
120
        }
121
122
        return $response;
123
    }
124
125
    /**
126
     * Create a widget.
127
     *
128
     * @param string $type              The type of the widget we edit
129
     * @param int    $viewReference     The view reference where attach the widget
130
     * @param string $slot              The slot where attach the widget
131
     * @param string $businessEntityId  The BusinessEntity::id (can be null if the submitted form is in static mode)
132
     *
133
     * @return JsonResponse
134
     * @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"})
135
     * @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"})
136
     * @Template()
137
     */
138
    public function createAction($mode, $type, $viewReference, $slot = null, $position = null, $widgetMapReference = null, $businessEntityId = null)
139
    {
140
        try {
141
            //services
142
            $view = $this->getViewByReferenceId($viewReference);
143
144
            $isNewPage = $view->getId() === null ? true : false;
145
146 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...
147
                ->getOneReferenceByParameters(['id' => $viewReference])) {
148
                $reference = new ViewReference($viewReference);
149
            }
150
151
            $view->setReference($reference);
152
            $this->get('victoire_core.current_view')->setCurrentView($view);
153
154
            $response = $this->get('widget_manager')->createWidget($mode, $type, $slot, $view, $businessEntityId, $position, $widgetMapReference);
155
156
            if ($isNewPage) {
157
                $response = new JsonResponse([
158
                    'success'  => true,
159
                    'redirect' => $this->generateUrl(
160
                        'victoire_core_page_show',
161
                        [
162
                            'url' => $reference->getUrl(),
163
                        ]
164
                    ),
165
                ]);
166
            } else {
167
                $response = new JsonResponse($response);
168
            }
169
        } catch (Exception $ex) {
170
            $response = $this->getJsonReponseFromException($ex);
171
        }
172
173
        return $response;
174
    }
175
176
    /**
177
     * Edit a widget.
178
     *
179
     * @param Widget $widget           The widget to edit
180
     * @param int    $viewReference    The current view
181
     * @param string $businessEntityId The BusinessEntity::id (can be null if the submitted form is in static mode)
182
     *
183
     * @return JsonResponse
184
     *
185
     * @Route("/victoire-dcms/widget/edit/{id}/{viewReference}/{mode}/{businessEntityId}", name="victoire_core_widget_edit", options={"expose"=true})
186
     * @Route("/victoire-dcms/widget/update/{id}/{viewReference}/{mode}/{businessEntityId}", name="victoire_core_widget_update", defaults={"businessEntityId": null})
187
     * @Template()
188
     */
189
    public function editAction(Widget $widget, $viewReference, $mode = Widget::MODE_STATIC, $businessEntityId = null)
190
    {
191
        $view = $this->getViewByReferenceId($viewReference);
192
        $this->get('victoire_widget_map.builder')->build($view, $this->get('doctrine.orm.entity_manager'));
193
        $widgetView = $view->getWidgetMapByWidget($widget)->getView();
194
        $this->get('victoire_widget_map.widget_data_warmer')->warm($this->getDoctrine()->getManager(), $view);
195
196
        if ($view instanceof BusinessTemplate && !$reference = $this->container->get('victoire_view_reference.repository')
197
            ->getOneReferenceByParameters(['viewId' => $view->getId()])) {
198
            $reference = new ViewReference($viewReference);
199
            $widgetView->setReference($reference);
200
        }
201
        $widget->setCurrentView($widgetView);
202
        $this->get('victoire_core.current_view')->setCurrentView($view);
203
        try {
204
            $response = new JsonResponse(
205
                $this->get('widget_manager')->editWidget(
206
                    $this->get('request'),
207
                    $widget,
208
                    $view,
209
                    $businessEntityId,
210
                    $mode
211
                )
212
            );
213
        } catch (Exception $ex) {
214
            $response = $this->getJsonReponseFromException($ex);
215
        }
216
217
        return $response;
218
    }
219
220
    /**
221
     * Stylize a widget.
222
     *
223
     * @param Widget $widget        The widget to stylize
224
     * @param int    $viewReference The current view
225
     *
226
     * @return JsonResponse
227
     *
228
     * @Route("/victoire-dcms/widget/stylize/{id}/{viewReference}", name="victoire_core_widget_stylize", options={"expose"=true})
229
     * @Template()
230
     */
231
    public function stylizeAction(Request $request, Widget $widget, $viewReference)
232
    {
233
        $view = $this->getViewByReferenceId($viewReference);
234
        $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...
235
236
        $widgetViewReference = $this->container->get('victoire_view_reference.repository')
237
            ->getOneReferenceByParameters(['viewId' => $view->getId()]);
238
239
        $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...
240
        $this->get('victoire_core.current_view')->setCurrentView($view);
241
        try {
242
            $form = $this->container->get('form.factory')->create('victoire_widget_style_type', $widget, [
243
                    'method' => 'POST',
244
                    'action' => $this->generateUrl(
245
                        'victoire_core_widget_stylize',
246
                        [
247
                            'id'            => $widget->getId(),
248
                            'viewReference' => $viewReference,
249
                        ]
250
                    ),
251
                ]
252
            );
253
            $form->handleRequest($this->get('request'));
254
255
            if ($request->query->get('novalidate', false) === false && $form->isValid()) {
256
                if ($form->has('deleteBackground') && $form->get('deleteBackground')->getData()) {
257
                    // @todo: dynamic responsive key
258
                    foreach (['', 'XS', 'SM', 'MD', 'LG'] as $key) {
259
                        $widget->{'deleteBackground'.$key}();
260
                    }
261
                }
262
                $this->get('doctrine.orm.entity_manager')->flush();
263
                $params = [
264
                    'view'        => $view,
265
                    'success'     => true,
266
                    'html'        => $this->get('victoire_widget.widget_renderer')->render($widget, $view),
267
                    'widgetId'    => $widget->getId(),
268
                    'viewCssHash' => $view->getCssHash(),
269
                ];
270
            } else {
271
                $template = ($request->query->get('novalidate', false) !== false) ? 'VictoireCoreBundle:Widget/Form/stylize:form.html.twig' : 'VictoireCoreBundle:Widget/Form:stylize.html.twig';
272
                $params = [
273
                    'success'  => false,
274
                    'html'     => $this->get('victoire_core.template_mapper')->render(
275
                        $template,
276
                        [
277
                            'view'   => $view,
278
                            'form'   => $form->createView(),
279
                            'widget' => $widget,
280
                        ]
281
                    ),
282
                ];
283
            }
284
            $response = new JsonResponse($params);
285
        } catch (Exception $ex) {
286
            $response = $this->getJsonReponseFromException($ex);
287
        }
288
289
        return $response;
290
    }
291
292
    /**
293
     * Delete a Widget.
294
     *
295
     * @param Widget $widget        The widget to delete
296
     * @param int    $viewReference The current view
297
     *
298
     * @return JsonResponse response
299
     * @Route("/victoire-dcms/widget/delete/{id}/{viewReference}", name="victoire_core_widget_delete", defaults={"_format": "json"})
300
     * @Template()
301
     */
302
    public function deleteAction(Widget $widget, $viewReference)
303
    {
304
        $view = $this->getViewByReferenceId($viewReference);
305
        try {
306
            $widgetId = $widget->getId();
307
            $this->get('widget_manager')->deleteWidget($widget, $view);
308
309
            return new JsonResponse([
310
                    'success'  => true,
311
                    'message'  => $this->get('translator')->trans('victoire_widget.delete.success', [], 'victoire'),
312
                    'widgetId' => $widgetId,
313
                ]
314
            );
315
        } catch (Exception $ex) {
316
            return $this->getJsonReponseFromException($ex);
317
        }
318
    }
319
320
    /**
321
     * Unlink a Widget by id
322
     * -> used to unlink an invalid widget after a bad widget unplug.
323
     *
324
     * @param int $id            The widgetId to unlink
325
     * @param int $viewReference The current viewReference
326
     *
327
     * @return JsonResponse response
328
     * @Route("/victoire-dcms/widget/unlink/{id}/{viewReference}", name="victoire_core_widget_unlink", defaults={"_format": "json"}, options={"expose"=true})
329
     * @Template()
330
     */
331
    public function unlinkAction($id, $viewReference)
332
    {
333
        $view = $this->getViewByReferenceId($viewReference);
334
        try {
335
            $this->get('victoire_widget.widget_helper')->deleteById($id);
336
            $this->get('doctrine.orm.entity_manager')->flush();
337
338
            if ($view instanceof Template) {
339
                $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...
340
            } elseif ($view instanceof BusinessTemplate) {
341
                $redirect = $this->generateUrl('victoire_business_template_show', ['id' => $view->getId()]);
342
            } else {
343
                $viewReference = $this->container->get('victoire_view_reference.repository')
344
                    ->getOneReferenceByParameters(['viewId' => $view->getId()]);
345
346
                $redirect = $this->generateUrl('victoire_core_page_show', [
347
                        'url' => $viewReference->getUrl(),
348
                    ]);
349
            }
350
351
            return new JsonResponse([
352
                    'success'  => true,
353
                    'redirect' => $redirect,
354
                ]);
355
        } catch (Exception $ex) {
356
            return $this->getJsonReponseFromException($ex);
357
        }
358
    }
359
360
    /**
361
     * Update widget positions accross the view. If moved widget is a Reference, ask to detach the view from template.
362
     *
363
     * @param int $viewReference The current viewReference
364
     *
365
     * @return JsonResponse
366
     * @Route("/victoire-dcms/widget/updatePosition/{viewReference}", name="victoire_core_widget_update_position", options={"expose"=true})
367
     */
368
    public function updatePositionAction(Request $request, $viewReference)
369
    {
370
        $view = $this->getViewByReferenceId($viewReference);
371
        try {
372
            //the sorted order for the widgets
373
            $sortedWidget = $request->get('sorted');
374
            $em = $this->get('doctrine.orm.entity_manager');
375
            if (!$view->getId()) {
376
                //This view does not have an id, so it's a non persisted BEP. To keep this new order, well have to persist it.
377
                $em->persist($view);
378
                $em->flush();
379
            }
380
            $this->get('victoire_widget_map.builder')->build($view);
381
            //recompute the order for the widgets
382
            $this->get('victoire_widget_map.manager')->move($view, $sortedWidget);
383
            $em->flush();
384
385
            $this->get('victoire_widget_map.builder')->build($view);
386
            $availablePositions = $this->get('victoire_widget_map.builder')->getAvailablePosition($view);
387
388
            $response = new JsonResponse(['success' => true, 'availablePositions' => $availablePositions]);
389
        } catch (Exception $ex) {
390
            $response = $this->getJsonReponseFromException($ex);
391
        }
392
393
        return $response;
394
    }
395
396
    /**
397
     * Update widget positions accross the view. If moved widget is a Reference, ask to detach the view from template.
398
     *
399
     * @param int $viewReference The current viewReference
400
     *
401
     * @return JsonResponse
402
     * @Route("/victoire-dcms/widget/get-available-positions/{viewReference}", name="victoire_core_widget_get_available_positions", options={"expose"=true})
403
     */
404
    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...
405
    {
406
        $view = $this->getViewByReferenceId($viewReference);
407
408
        $this->get('victoire_widget_map.builder')->build($view);
409
        $availablePositions = $this->get('victoire_widget_map.builder')->getAvailablePosition($view);
410
411
        return new JsonResponse($availablePositions);
412
    }
413
414
    /**
415
     * Get the json response by the exception and the current user.
416
     *
417
     * @param Exception $ex
418
     *
419
     * @return JsonResponse
420
     */
421
    protected function getJsonReponseFromException(Exception $ex)
422
    {
423
        //services
424
        $securityContext = $this->get('security.context');
425
        $logger = $this->get('logger');
426
427
        //can we see the debug
428
        $isDebugAllowed = $securityContext->isGranted('ROLE_VICTOIRE_PAGE_DEBUG');
429
430
        //whatever is the exception, we log it
431
        $logger->error($ex->getMessage());
432
        $logger->error($ex->getTraceAsString());
433
434
        if ($isDebugAllowed) {
435
            throw $ex;
436
        } else {
437
            //translate the message
438
            $translator = $this->get('translator');
439
440
            //get the translated message
441
            $message = $translator->trans('error_occured', [], 'victoire');
442
443
            $response = new JsonResponse(
444
                [
445
                    'success' => false,
446
                    'message' => $message,
447
                ]
448
            );
449
        }
450
451
        return $response;
452
    }
453
454
    /**
455
     * @param int $referenceId
456
     */
457
    protected function getViewByReferenceId($referenceId)
458
    {
459
        return $this->get('victoire_page.page_helper')->findPageByParameters(['id' => $referenceId]);
460
    }
461
}
462