Passed
Push — master ( 1029e9...94b881 )
by
unknown
05:14
created

lib/Thelia/Controller/Admin/ProfileController.php (2 issues)

Severity
1
<?php
2
/*************************************************************************************/
3
/*      This file is part of the Thelia package.                                     */
4
/*                                                                                   */
5
/*      Copyright (c) OpenStudio                                                     */
6
/*      email : [email protected]                                                       */
7
/*      web : http://www.thelia.net                                                  */
8
/*                                                                                   */
9
/*      For the full copyright and license information, please view the LICENSE.txt  */
10
/*      file that was distributed with this source code.                             */
11
/*************************************************************************************/
12
13
namespace Thelia\Controller\Admin;
14
15
use Thelia\Core\Event\Profile\ProfileEvent;
16
use Thelia\Core\Event\TheliaEvents;
17
use Thelia\Core\HttpFoundation\Response;
18
use Thelia\Core\Security\AccessManager;
19
use Thelia\Core\Security\Resource\AdminResources;
20
use Thelia\Form\Definition\AdminForm;
21
use Thelia\Form\Exception\FormValidationException;
22
use Thelia\Form\ProfileUpdateModuleAccessForm;
23
use Thelia\Form\ProfileUpdateResourceAccessForm;
24
use Thelia\Model\Profile;
25
use Thelia\Model\ProfileQuery;
26
27
class ProfileController extends AbstractCrudController
28
{
29
    public function __construct()
30
    {
31
        parent::__construct(
32
            'profile',
33
            'manual',
34
            'order',
35
            AdminResources::PROFILE,
36
            TheliaEvents::PROFILE_CREATE,
37
            TheliaEvents::PROFILE_UPDATE,
38
            TheliaEvents::PROFILE_DELETE
39
        );
40
    }
41
42
    protected function getCreationForm()
43
    {
44
        return $this->createForm(AdminForm::PROFILE_CREATION);
45
    }
46
47
    protected function getUpdateForm()
48
    {
49
        return $this->createForm(AdminForm::PROFILE_MODIFICATION);
50
    }
51
52
    protected function getCreationEvent($formData)
53
    {
54
        $event = new ProfileEvent();
55
56
        $event->setLocale($formData['locale']);
57
        $event->setCode($formData['code']);
58
        $event->setTitle($formData['title']);
59
        $event->setChapo($formData['chapo']);
60
        $event->setDescription($formData['description']);
61
        $event->setPostscriptum($formData['postscriptum']);
62
63
        return $event;
64
    }
65
66
    protected function getUpdateEvent($formData)
67
    {
68
        $event = new ProfileEvent();
69
70
        $event->setLocale($formData['locale']);
71
        $event->setId($formData['id']);
72
        $event->setTitle($formData['title']);
73
        $event->setChapo($formData['chapo']);
74
        $event->setDescription($formData['description']);
75
        $event->setPostscriptum($formData['postscriptum']);
76
77
        return $event;
78
    }
79
80
    protected function getDeleteEvent()
81
    {
82
        $event = new ProfileEvent();
83
84
        $event->setId(
85
            $this->getRequest()->get('profile_id', 0)
86
        );
87
88
        return $event;
89
    }
90
91
    /**
92
     * @param ProfileEvent $event
93
     * @return boolean
94
     */
95
    protected function eventContainsObject($event)
96
    {
97
        return $event->hasProfile();
98
    }
99
100
    /**
101
     * @param Profile $object
102
     * @return \Thelia\Form\BaseForm
103
     */
104
    protected function hydrateObjectForm($object)
105
    {
106
        $data = array(
107
            'id'           => $object->getId(),
108
            'locale'       => $object->getLocale(),
109
            'title'        => $object->getTitle(),
110
            'description'  => $object->getDescription(),
111
            'code'         => $object->getCode(),
112
        );
113
114
        // Setup the object form
115
        return $this->createForm(AdminForm::PROFILE_MODIFICATION, "form", $data);
116
    }
117
118
    /**
119
     * @param Profile $object
120
     * @return \Thelia\Form\BaseForm
121
     */
122
    protected function hydrateResourceUpdateForm($object)
123
    {
124
        $data = array(
125
            'id'           => $object->getId(),
126
        );
127
128
        // Setup the object form
129
        return $this->createForm(AdminForm::PROFILE_UPDATE_RESOURCE_ACCESS, "form", $data);
130
    }
131
132
    /**
133
     * @param Profile $object
134
     * @return \Thelia\Form\BaseForm
135
     */
136
    protected function hydrateModuleUpdateForm($object)
137
    {
138
        $data = array(
139
            'id'           => $object->getId(),
140
        );
141
142
        // Setup the object form
143
        return $this->createForm(AdminForm::PROFILE_UPDATE_MODULE_ACCESS, "form", $data);
144
    }
145
146
    protected function getObjectFromEvent($event)
147
    {
148
        return $event->hasProfile() ? $event->getProfile() : null;
149
    }
150
151
    protected function getExistingObject()
152
    {
153
        $profile = ProfileQuery::create()
154
            ->findOneById($this->getRequest()->get('profile_id', 0));
155
156
        if (null !== $profile) {
157
            $profile->setLocale($this->getCurrentEditionLocale());
158
        }
159
160
        return $profile;
161
    }
162
163
    /**
164
     * @param Profile $object
165
     * @return string
166
     */
167
    protected function getObjectLabel($object)
168
    {
169
        return $object->getTitle();
170
    }
171
172
    /**
173
     * @param Profile $object
174
     * @return int
175
     */
176
    protected function getObjectId($object)
177
    {
178
        return $object->getId();
179
    }
180
181
    protected function getViewArguments()
182
    {
183
        return (null !== $tab = $this->getRequest()->get('tab')) ? [ 'tab' => $tab ] : [];
184
    }
185
186
    protected function getRouteArguments($profile_id = null)
187
    {
188
        return array(
189
            'profile_id' => $profile_id === null ? $this->getRequest()->get('profile_id') : $profile_id,
190
        );
191
    }
192
193
    protected function renderListTemplate($currentOrder)
194
    {
195
        // We always return to the feature edition form
196
        return $this->render(
197
            'profiles',
198
            array()
199
        );
200
    }
201
202
    protected function renderEditionTemplate()
203
    {
204
        // We always return to the feature edition form
205
        return $this->render('profile-edit', array_merge($this->getViewArguments(), $this->getRouteArguments()));
206
    }
207
208
    protected function redirectToEditionTemplate()
209
    {
210
        // We always return to the feature edition form
211
        return $this->generateRedirectFromRoute(
212
            "admin.configuration.profiles.update",
213
            $this->getViewArguments(),
214
            $this->getRouteArguments()
215
        );
216
    }
217
218
    /**
219
     * Put in this method post object creation processing if required.
220
     *
221
     * @param  ProfileEvent $createEvent the create event
222
     * @return \Symfony\Component\HttpFoundation\Response|Response
223
     */
224
    protected function performAdditionalCreateAction($createEvent)
225
    {
226
        return $this->generateRedirectFromRoute(
227
            "admin.configuration.profiles.update",
228
            $this->getViewArguments(),
229
            $this->getRouteArguments($createEvent->getProfile()->getId())
230
        );
231
    }
232
233
    protected function redirectToListTemplate()
234
    {
235
        return $this->generateRedirectFromRoute("admin.configuration.profiles.list");
236
    }
237
238
    public function updateAction()
239
    {
240
        if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) {
241
            return $response;
242
        }
243
244
        $object = $this->getExistingObject();
245
246
        if ($object != null) {
247
            // Hydrate the form and pass it to the parser
248
            $resourceAccessForm = $this->hydrateResourceUpdateForm($object);
249
            $moduleAccessForm = $this->hydrateModuleUpdateForm($object);
250
251
            // Pass it to the parser
252
            $this->getParserContext()->addForm($resourceAccessForm);
253
            $this->getParserContext()->addForm($moduleAccessForm);
254
        }
255
256
        return parent::updateAction();
257
    }
258
259
    protected function getUpdateResourceAccessEvent($formData)
260
    {
261
        $event = new ProfileEvent();
262
263
        $event->setId($formData['id']);
264
        $event->setResourceAccess($this->getResourceAccess($formData));
265
266
        return $event;
267
    }
268
269
    protected function getUpdateModuleAccessEvent($formData)
270
    {
271
        $event = new ProfileEvent();
272
273
        $event->setId($formData['id']);
274
        $event->setModuleAccess($this->getModuleAccess($formData));
275
276
        return $event;
277
    }
278
279
    protected function getResourceAccess($formData)
280
    {
281
        $requirements = array();
282
        foreach ($formData as $data => $value) {
283
            if (!strstr($data, ':')) {
284
                continue;
285
            }
286
287
            $explosion = explode(':', $data);
288
289
            $prefix = array_shift($explosion);
290
291
            if ($prefix != ProfileUpdateResourceAccessForm::RESOURCE_ACCESS_FIELD_PREFIX) {
292
                continue;
293
            }
294
295
            $requirements[implode('.', $explosion)] = $value;
296
        }
297
298
        return $requirements;
299
    }
300
301
    protected function getModuleAccess($formData)
302
    {
303
        $requirements = array();
304
        foreach ($formData as $data => $value) {
305
            if (!strstr($data, ':')) {
306
                continue;
307
            }
308
309
            $explosion = explode(':', $data);
310
311
            $prefix = array_shift($explosion);
312
313
            if ($prefix != ProfileUpdateModuleAccessForm::MODULE_ACCESS_FIELD_PREFIX) {
314
                continue;
315
            }
316
317
            $requirements[implode('.', $explosion)] = $value;
318
        }
319
320
        return $requirements;
321
    }
322
323
    public function processUpdateResourceAccess()
324
    {
325
        // Check current user authorization
326
        if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) {
327
            return $response;
328
        }
329
330
        // Create the form from the request
331
        $changeForm = $this->createForm(AdminForm::PROFILE_UPDATE_RESOURCE_ACCESS);
332
333
        try {
334
            // Check the form against constraints violations
335
            $form = $this->validateForm($changeForm, "POST");
336
337
            // Get the form field values
338
            $data = $form->getData();
339
340
            $changeEvent = $this->getUpdateResourceAccessEvent($data);
341
342
            $this->dispatch(TheliaEvents::PROFILE_RESOURCE_ACCESS_UPDATE, $changeEvent);
343
344
            if (! $this->eventContainsObject($changeEvent)) {
345
                throw new \LogicException(
346
                    $this->getTranslator()->trans("No %obj was updated.", array('%obj', $this->objectName))
347
                );
348
            }
349
350
            // Log object modification
351
            if (null !== $changedObject = $this->getObjectFromEvent($changeEvent)) {
352
                $this->adminLogAppend(
353
                    $this->resourceCode,
354
                    AccessManager::UPDATE,
355
                    sprintf(
356
                        "%s %s (ID %s) modified",
357
                        ucfirst($this->objectName),
358
                        $this->getObjectLabel($changedObject),
359
                        $this->getObjectId($changedObject)
360
                    ),
361
                    $this->getObjectId($changedObject)
362
                );
363
            }
364
365
            if ($response == null) {
0 ignored issues
show
The condition $response == null is always true.
Loading history...
366
                return $this->redirectToEditionTemplate();
367
            } else {
368
                return $response;
369
            }
370
        } catch (FormValidationException $ex) {
371
            // Form cannot be validated
372
            $error_msg = $this->createStandardFormValidationErrorMessage($ex);
373
        } catch (\Exception $ex) {
374
            // Any other error
375
            $error_msg = $ex->getMessage();
376
        }
377
378
        $this->setupFormErrorContext($this->getTranslator()->trans("%obj modification", array('%obj' => 'taxrule')), $error_msg, $changeForm, $ex);
379
380
        // At this point, the form has errors, and should be redisplayed.
381
        return $this->renderEditionTemplate();
382
    }
383
384
    public function processUpdateModuleAccess()
385
    {
386
        // Check current user authorization
387
        if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) {
388
            return $response;
389
        }
390
391
        // Create the form from the request
392
        $changeForm = $this->createForm(AdminForm::PROFILE_UPDATE_MODULE_ACCESS);
393
394
        try {
395
            // Check the form against constraints violations
396
            $form = $this->validateForm($changeForm, "POST");
397
398
            // Get the form field values
399
            $data = $form->getData();
400
401
            $changeEvent = $this->getUpdateModuleAccessEvent($data);
402
403
            $this->dispatch(TheliaEvents::PROFILE_MODULE_ACCESS_UPDATE, $changeEvent);
404
405
            if (! $this->eventContainsObject($changeEvent)) {
406
                throw new \LogicException(
407
                    $this->getTranslator()->trans("No %obj was updated.", array('%obj', $this->objectName))
408
                );
409
            }
410
411
            // Log object modification
412
            if (null !== $changedObject = $this->getObjectFromEvent($changeEvent)) {
413
                $this->adminLogAppend(
414
                    $this->resourceCode,
415
                    AccessManager::UPDATE,
416
                    sprintf(
417
                        "%s %s (ID %s) modified",
418
                        ucfirst($this->objectName),
419
                        $this->getObjectLabel($changedObject),
420
                        $this->getObjectId($changedObject)
421
                    ),
422
                    $this->getObjectId($changedObject)
423
                );
424
            }
425
426
            if ($response == null) {
0 ignored issues
show
The condition $response == null is always true.
Loading history...
427
                return $this->redirectToEditionTemplate();
428
            } else {
429
                return $response;
430
            }
431
        } catch (FormValidationException $ex) {
432
            // Form cannot be validated
433
            $error_msg = $this->createStandardFormValidationErrorMessage($ex);
434
        } catch (\Exception $ex) {
435
            // Any other error
436
            $error_msg = $ex->getMessage();
437
        }
438
439
        $this->setupFormErrorContext($this->getTranslator()->trans("%obj modification", array('%obj' => 'taxrule')), $error_msg, $changeForm, $ex);
440
441
        // At this point, the form has errors, and should be redisplayed.
442
        return $this->renderEditionTemplate();
443
    }
444
}
445