Completed
Push — master ( 5d51b4...87fdd9 )
by Paul
10s
created

BusinessTemplateController::editAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 22
Code Lines 13

Duplication

Lines 22
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 22
loc 22
rs 9.2
cc 1
eloc 13
nc 1
nop 1
1
<?php
2
3
namespace Victoire\Bundle\BusinessPageBundle\Controller;
4
5
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
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\BusinessPageBundle\Form\BusinessTemplateType;
15
use Victoire\Bundle\CoreBundle\Controller\VictoireAlertifyControllerTrait;
16
use Victoire\Bundle\CoreBundle\Entity\View;
17
use Victoire\Bundle\ViewReferenceBundle\ViewReference\ViewReference;
18
19
/**
20
 * BusinessTemplate controller.
21
 *
22
 * @Route("/victoire-dcms/business-template")
23
 */
24
class BusinessTemplateController extends Controller
25
{
26
    use VictoireAlertifyControllerTrait;
27
28
    /**
29
     * List all business entity page pattern.
30
     *
31
     * @Route("/", name="victoire_business_template_index")
32
     *
33
     * @return JsonResponse
34
     */
35
    public function indexAction()
36
    {
37
        $businessEntityHelper = $this->get('victoire_core.helper.business_entity_helper');
38
39
        //services
40
        $em = $this->get('doctrine.orm.entity_manager');
41
42
        //the repository
43
        $repository = $em->getRepository('VictoireBusinessPageBundle:BusinessTemplate');
44
45
        $BusinessTemplates = [];
46
47
        $businessEntities = $businessEntityHelper->getBusinessEntities();
48
49
        foreach ($businessEntities as $businessEntity) {
50
            $name = $businessEntity->getName();
51
52
            //retrieve the pagePatterns
53
            $pagePatterns = $repository->findPagePatternByBusinessEntity($businessEntity);
54
55
            $BusinessTemplates[$name] = $pagePatterns;
56
        }
57
58
        return new JsonResponse([
59
                'html'    => $this->container->get('templating')->render(
60
                    'VictoireBusinessPageBundle:BusinessEntity:index.html.twig',
61
                    [
62
                        'businessEntities'           => $businessEntities,
63
                        'BusinessTemplates'          => $BusinessTemplates,
64
                    ]
65
                ),
66
                'success' => true,
67
            ]);
68
    }
69
70
    /**
71
     * show BusinessTemplate.
72
     *
73
     * @Route("/show/{id}", name="victoire_business_template_show")
74
     * @ParamConverter("template", class="VictoireBusinessPageBundle:BusinessTemplate")
75
     *
76
     * @return Response
77
     */
78
    public function showAction(BusinessTemplate $view)
79
    {
80
        //add the view to twig
81
        $this->get('twig')->addGlobal('view', $view);
82
        $view->setReference(new ViewReference($view->getId()));
83
84
        $this->get('victoire_widget_map.builder')->build($view);
85
        $this->get('victoire_widget_map.widget_data_warmer')->warm(
86
            $this->get('doctrine.orm.entity_manager'),
87
            $view
88
        );
89
90
        $this->container->get('victoire_core.current_view')->setCurrentView($view);
91
92
        return $this->container->get('victoire_page.page_helper')->renderPage($view);
93
    }
94
95
    /**
96
     * Creates a new BusinessTemplate entity.
97
     *
98
     * @param Request $request
99
     * @param int     $id
100
     *
101
     * @Route("{id}/create", name="victoire_business_template_create")
102
     * @Method("POST")
103
     * @Template("VictoireBusinessPageBundle:BusinessTemplate:new.html.twig")
104
     *
105
     * @return JsonResponse
106
     */
107
    public function createAction(Request $request, $id)
108
    {
109
        //get the business entity
110
        $businessEntity = $this->getBusinessEntity($id);
111
112
        /** @var BusinessTemplate $view */
113
        $view = $this->get('victoire_business_page.BusinessTemplate_chain')->getBusinessTemplate($id);
114
        $view->setBusinessEntityId($businessEntity->getId());
115
116
        $form = $this->createCreateForm($view);
117
118
        $form->handleRequest($request);
119
120
        $params = [
121
            'success' => false,
122
        ];
123
124
        if ($form->isValid()) {
125
            $em = $this->getDoctrine()->getManager();
126
            $em->persist($view);
127
            $em->flush();
128
129
            //redirect to the page of the pagePattern
130
            $params['url'] = $this->generateUrl('victoire_business_template_show', ['id' => $view->getId()]);
131
            $params['success'] = true;
132
133
            $this->congrat($this->get('translator')->trans('victoire.business_template.create.success', [], 'victoire'));
134
        } else {
135
            //get the errors as a string
136
            $params['message'] = $this->container->get('victoire_form.error_helper')->getRecursiveReadableErrors($form);
137
        }
138
139
        return new JsonResponse($params);
140
    }
141
142
    /**
143
     * Creates a form to create a BusinessTemplate entity.
144
     *
145
     * @param BusinessTemplate $view The entity
146
     *
147
     * @return \Symfony\Component\Form\Form The form
148
     * @return Form
149
     */
150 View Code Duplication
    private function createCreateForm(BusinessTemplate $view)
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...
151
    {
152
        $id = $view->getBusinessEntityId();
153
154
        $businessProperties = $this->getBusinessProperties($view);
155
        $form = $this->createForm(
156
            BusinessTemplateType::class,
157
            $view,
158
            [
159
                'action'                  => $this->generateUrl('victoire_business_template_create', ['id' => $id]),
160
                'method'                  => 'POST',
161
                'vic_business_properties' => $businessProperties,
162
            ]
163
        );
164
165
        return $form;
166
    }
167
168
    /**
169
     * Displays a form to create a new BusinessTemplate entity.
170
     *
171
     * @param string $id The id of the businessEntity
172
     *
173
     * @Route("/{id}/new", name="victoire_business_template_new")
174
     * @Method("GET")
175
     * @Template()
176
     *
177
     * @return JsonResponse The entity and the form
178
     */
179 View Code Duplication
    public function newAction($id)
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...
180
    {
181
        //get the business entity
182
        $businessEntity = $this->getBusinessEntity($id);
183
184
        /** @var BusinessTemplate $view */
185
        $view = $this->get('victoire_business_page.BusinessTemplate_chain')->getBusinessTemplate($id);
186
        $view->setBusinessEntityId($businessEntity->getId());
187
188
        $form = $this->createCreateForm($view);
189
190
        $parameters = [
191
            'entity'             => $view,
192
            'form'               => $form->createView(),
193
        ];
194
195
        return new JsonResponse([
196
            'html' => $this->container->get('templating')->render(
197
                'VictoireBusinessPageBundle:BusinessTemplate:new.html.twig',
198
                $parameters
199
            ),
200
            'success' => true,
201
        ]);
202
    }
203
204
    /**
205
     * Displays a form to edit an existing BusinessTemplate entity.
206
     *
207
     * @Route("/{id}/edit", name="victoire_business_template_edit")
208
     * @Method("GET")
209
     * @Template()
210
     * @ParamConverter("id", class="VictoireCoreBundle:View")
211
     *
212
     * @throws \Exception
213
     *
214
     * @return JsonResponse The entity and the form
215
     */
216 View Code Duplication
    public function editAction(View $view)
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...
217
    {
218
        $em = $this->getDoctrine()->getManager();
0 ignored issues
show
Unused Code introduced by
$em is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
219
220
        $editForm = $this->createEditForm($view);
0 ignored issues
show
Compatibility introduced by
$view of type object<Victoire\Bundle\CoreBundle\Entity\View> is not a sub-type of object<Victoire\Bundle\B...ntity\BusinessTemplate>. It seems like you assume a child class of the class Victoire\Bundle\CoreBundle\Entity\View to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
221
        $deleteForm = $this->createDeleteForm($view->getId());
222
223
224
        $parameters = [
225
            'entity'             => $view,
226
            'form'               => $editForm->createView(),
227
            'delete_form'        => $deleteForm->createView(),
228
        ];
229
230
        return new JsonResponse([
231
            'html' => $this->container->get('templating')->render(
232
                'VictoireBusinessPageBundle:BusinessTemplate:edit.html.twig',
233
                $parameters
234
            ),
235
            'success' => true,
236
        ]);
237
    }
238
239
    /**
240
     * Creates a form to edit a BusinessTemplate entity.
241
     *
242
     * @param BusinessTemplate $view The entity
243
     *
244
     * @return \Symfony\Component\Form\Form The form
245
     */
246 View Code Duplication
    private function createEditForm(BusinessTemplate $view)
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...
247
    {
248
        $businessProperties = $this->getBusinessProperties($view);
249
250
        $form = $this->createForm(BusinessTemplateType::class, $view, [
251
            'action'                  => $this->generateUrl('victoire_business_template_update', ['id' => $view->getId()]),
252
            'method'                  => 'PUT',
253
            'vic_business_properties' => $businessProperties,
254
        ]);
255
256
        return $form;
257
    }
258
259
    /**
260
     * Edits an existing BusinessTemplate entity.
261
     *
262
     * @param Request $request
263
     * @param string  $id
264
     *
265
     * @Route("/{id}", name="victoire_business_template_update")
266
     * @Method("PUT")
267
     * @Template("VictoireBusinessPageBundle:BusinessTemplate:edit.html.twig")
268
     *
269
     * @throws \Exception
270
     *
271
     * @return JsonResponse The parameter for the response
272
     */
273
    public function updateAction(Request $request, $id)
274
    {
275
        $em = $this->getDoctrine()->getManager();
276
277
        /** @var BusinessTemplate $pagePattern */
278
        $pagePattern = $em->getRepository('VictoireBusinessPageBundle:BusinessTemplate')->find($id);
279
280
        if (!$pagePattern) {
281
            throw $this->createNotFoundException('Unable to find BusinessTemplate entity.');
282
        }
283
284
        $editForm = $this->createEditForm($pagePattern);
285
        $editForm->handleRequest($request);
286
287
        if ($editForm->isValid()) {
288
            $em->flush();
289
290
            //redirect to the page of the template
291
            $completeUrl = $this->generateUrl('victoire_business_template_show', ['id' => $pagePattern->getId()]);
292
            $message = $this->get('translator')->trans('victoire.business_template.edit.success', [], 'victoire');
293
294
            $success = true;
295
        } else {
296
            $success = false;
297
            $completeUrl = null;
298
            $message = $this->get('translator')->trans('victoire.business_template.edit.error', [], 'victoire');
299
        }
300
301
        return new JsonResponse([
302
            'success' => $success,
303
            'url'     => $completeUrl,
304
            'message' => $message,
305
        ]);
306
    }
307
308
    /**
309
     * Deletes a BusinessTemplate entity.
310
     *
311
     * @param Request $request
312
     * @param string  $id
313
     *
314
     * @Route("/{id}", name="victoire_business_template_delete")
315
     * @Method("DELETE")
316
     *
317
     * @throws \Exception
318
     *
319
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
320
     */
321 View Code Duplication
    public function deleteAction(Request $request, $id)
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...
322
    {
323
        $form = $this->createDeleteForm($id);
324
        $form->handleRequest($request);
325
326
        if ($form->isValid()) {
327
            $em = $this->getDoctrine()->getManager();
328
            $view = $em->getRepository('VictoireBusinessPageBundle:BusinessTemplate')->find($id);
329
330
            if (!$view) {
331
                throw $this->createNotFoundException('Unable to find BusinessTemplate entity.');
332
            }
333
334
            $em->remove($view);
335
            $em->flush();
336
        }
337
338
        return $this->redirect($this->generateUrl('victoire_business_template_index'));
339
    }
340
341
    /**
342
     * Creates a form to delete a BusinessTemplate entity by id.
343
     *
344
     * @param string $id The entity id
345
     *
346
     * @return \Symfony\Component\Form\Form The form
347
     */
348 View Code Duplication
    private function createDeleteForm($id)
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...
349
    {
350
        return $this->createFormBuilder()
351
            ->setAction($this->generateUrl('victoire_business_template_delete', ['id' => $id]))
352
            ->setMethod('DELETE')
353
            ->add('submit', 'submit', ['label' => 'Delete'])
354
            ->getForm();
355
    }
356
357
    /**
358
     * List the entities that matches the query of the BusinessTemplate.
359
     *
360
     * @param BusinessTemplate $view
361
     *
362
     * @Route("/listEntities/{id}", name="victoire_business_template_listentities")
363
     * @ParamConverter("id", class="VictoireBusinessPageBundle:BusinessTemplate")
364
     * @Template
365
     *
366
     * @throws Exception
367
     *
368
     * @return array|Response The list of items for this template
369
     */
370
    public function listEntitiesAction(BusinessTemplate $view)
371
    {
372
        //services
373
        $bepHelper = $this->get('victoire_business_page.business_page_helper');
374
375
        //parameters for the view
376
        return [
377
            'BusinessTemplate'          => $view,
378
            'items'                     => $bepHelper->getEntitiesAllowed($view, $this->get('doctrine.orm.entity_manager')),
379
        ];
380
    }
381
382
    /**
383
     * Get an array of business properties by the business entity page pattern.
384
     *
385
     * @param BusinessTemplate $view
386
     *
387
     * @return array of business properties
388
     */
389
    private function getBusinessProperties(BusinessTemplate $view)
390
    {
391
        $businessTemplateHelper = $this->get('victoire_business_page.business_page_helper');
392
        //the business property link to the page
393
        $businessEntityId = $view->getBusinessEntityId();
394
        $businessEntity = $this->get('victoire_core.helper.business_entity_helper')->findById($businessEntityId);
395
396
        $businessProperties = $businessTemplateHelper->getBusinessProperties($businessEntity);
397
398
        return $businessProperties;
399
    }
400
401
    /**
402
     * @param string $id The id of the business entity
403
     *
404
     * @throws Exception If the business entity was not found
405
     *
406
     * @return template
407
     */
408 View Code Duplication
    private function getBusinessEntity($id)
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...
409
    {
410
        //services
411
        $businessEntityManager = $this->get('victoire_core.helper.business_entity_helper');
412
413
        //get the businessEntity
414
        $businessEntity = $businessEntityManager->findById($id);
415
416
        //test the result
417
        if ($businessEntity === null) {
418
            throw new \Exception('The business entity ['.$id.'] was not found.');
419
        }
420
421
        return $businessEntity;
422
    }
423
}
424