BaseController   A
last analyzed

Complexity

Total Complexity 33

Size/Duplication

Total Lines 359
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 33
lcom 1
cbo 0
dl 0
loc 359
rs 9.76
c 0
b 0
f 0

18 Methods

Rating   Name   Duplication   Size   Complexity  
getListRenderTemplate() 0 1 ?
redirectToListTemplate() 0 1 ?
getEditRenderTemplate() 0 1 ?
getCreateRenderTemplate() 0 1 ?
getObjectId() 0 1 ?
getExistingObject() 0 1 ?
hydrateObjectForm() 0 1 ?
A defaultAction() 0 11 2
B createAction() 0 52 5
A updateAction() 0 21 3
B processUpdateAction() 0 66 7
A deleteAction() 0 30 4
A getService() 0 8 2
A getCreationForm() 0 4 1
A getUpdateForm() 0 8 2
A renderAfterDeleteError() 0 13 1
A checkUserAccessDealer() 0 15 3
A getAdminDealer() 0 14 3
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
14
namespace Dealer\Controller\Base;
15
16
use Dealer\Dealer;
17
use Dealer\Model\DealerQuery;
18
use Propel\Generator\Model\Database;
19
use Propel\Runtime\Propel;
20
use Symfony\Component\HttpFoundation\RedirectResponse;
21
use Thelia\Controller\Admin\BaseAdminController;
22
use Thelia\Core\Security\AccessManager;
23
use Thelia\Core\Security\Resource\AdminResources;
24
use Thelia\Core\Thelia;
25
use Thelia\Form\Exception\FormValidationException;
26
use Thelia\Tools\URL;
27
28
/**
29
 * Class BaseController
30
 * @package Dealer\Controller\Base
31
 */
32
abstract class BaseController extends BaseAdminController
33
{
34
    protected $useFallbackTemplate = true;
35
    /**
36
     * Name of entity associated with controller
37
     */
38
    const CONTROLLER_ENTITY_NAME = null;
39
    /**
40
     * Name of resource to check
41
     */
42
    const CONTROLLER_CHECK_RESOURCE = '';
43
44
    /**
45
     * Current Service Associated to controller
46
     */
47
    protected $service;
48
49
50
    // ABSTRACT FUNCTIONS
51
52
    /**
53
     * Use to get render of list
54
     * @return mixed
55
     */
56
    abstract protected function getListRenderTemplate();
57
58
    /**
59
     * Must return a RedirectResponse instance
60
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
61
     */
62
    abstract protected function redirectToListTemplate();
63
64
    /**
65
     * Use to get Edit render
66
     * @return mixed
67
     */
68
    abstract protected function getEditRenderTemplate();
69
70
    /**
71
     * Use to get Create render
72
     * @return mixed
73
     */
74
    abstract protected function getCreateRenderTemplate();
75
76
    /**
77
     * @return mixed
78
     */
79
    abstract protected function getObjectId($object);
80
81
    /**
82
     * Load an existing object from the database
83
     */
84
    abstract protected function getExistingObject();
85
86
    /**
87
     * Hydrate the update form for this object, before passing it to the update template
88
     *
89
     * @param mixed $object
90
     */
91
    abstract protected function hydrateObjectForm($object);
92
93
94
    // PUBLIC METHODS
95
96
    /**
97
     * The default action is displaying the list.
98
     *
99
     * @return \Thelia\Core\HttpFoundation\Response the response
100
     */
101
    public function defaultAction()
102
    {
103
        // Check current user authorization
104
        if (null !== $response = $this->checkAuth(static::CONTROLLER_CHECK_RESOURCE, Dealer::getModuleCode(),
105
                AccessManager::VIEW)
106
        ) {
107
            return $response;
108
        }
109
110
        return $this->getListRenderTemplate();
111
    }
112
113
    /**
114
     * Create an object
115
     * @return mixed|\Symfony\Component\HttpFoundation\Response
116
     */
117
    public function createAction()
118
    {
119
        // Check current user authorization
120
        if (null !== $response = $this->checkAuth(static::CONTROLLER_CHECK_RESOURCE, Dealer::getModuleCode(),
121
                AccessManager::CREATE)
122
        ) {
123
            return $response;
124
        }
125
126
        // Create the Creation Form
127
        $creationForm = $this->getCreationForm($this->getRequest());
128
129
        $con = Propel::getConnection();
130
        $con->beginTransaction();
131
132
        try {
133
            // Check the form against constraints violations
134
            $form = $this->validateForm($creationForm, "POST");
135
            // Get the form field values
136
            $data = $form->getData();
137
138
            $createdObject = $this->getService()->createFromArray($data, $this->getCurrentEditionLocale());
139
140
141
            // Substitute _ID_ in the URL with the ID of the created object
142
            $successUrl = str_replace('_ID_', $this->getObjectId($createdObject), $creationForm->getSuccessUrl());
143
144
            $con->commit();
145
146
            // Redirect to the success URL
147
            return $this->generateRedirect($successUrl);
148
        } catch (FormValidationException $ex) {
0 ignored issues
show
Bug introduced by
The class Thelia\Form\Exception\FormValidationException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
149
            $con->rollBack();
150
            // Form cannot be validated
151
            $error_msg = $this->createStandardFormValidationErrorMessage($ex);
152
        } catch (\Exception $ex) {
153
            $con->rollBack();
154
            // Any other error
155
            $error_msg = $ex->getMessage();
156
        }
157
        if (false !== $error_msg) {
158
            $this->setupFormErrorContext(
159
                $this->getTranslator()->trans("%obj creation", ['%obj' => static::CONTROLLER_ENTITY_NAME]),
160
                $error_msg,
161
                $creationForm,
162
                $ex
163
            );
164
165
            // At this point, the form has error, and should be redisplayed.
166
            return $this->getListRenderTemplate();
167
        }
168
    }
169
170
    /**
171
     * Load a object for modification, and display the edit template.
172
     *
173
     * @return \Thelia\Core\HttpFoundation\Response the response
174
     */
175
    public function updateAction()
176
    {
177
        // Check current user authorization
178
        if (null !== $response = $this->checkAuth(static::CONTROLLER_CHECK_RESOURCE, Dealer::getModuleCode(),
179
                AccessManager::UPDATE)
180
        ) {
181
            return $response;
182
        }
183
184
        // Load object if exist
185
        if (null !== $object = $this->getExistingObject()) {
186
            // Hydrate the form abd pass it to the parser
187
            $changeForm = $this->hydrateObjectForm($object);
188
189
            // Pass it to the parser
190
            $this->getParserContext()->addForm($changeForm);
191
        }
192
193
        // Render the edition template.
194
        return $this->getEditRenderTemplate();
195
    }
196
197
    /**
198
     * Save changes on a modified object, and either go back to the object list, or stay on the edition page.
199
     *
200
     * @return \Thelia\Core\HttpFoundation\Response the response
201
     */
202
    public function processUpdateAction()
203
    {
204
        // Check current user authorization
205
        if (null !== $response = $this->checkAuth(static::CONTROLLER_CHECK_RESOURCE, Dealer::getModuleCode(),
206
                AccessManager::UPDATE)
207
        ) {
208
            return $response;
209
        }
210
211
        // Error (Default: false)
212
        $error_msg = false;
0 ignored issues
show
Unused Code introduced by
$error_msg 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...
213
214
        // Create the Form from the request
215
        $changeForm = $this->getUpdateForm($this->getRequest());
216
217
218
        $con = Propel::getConnection();
219
        $con->beginTransaction();
220
221
        try {
222
            // Check the form against constraints violations
223
            $form = $this->validateForm($changeForm, "POST");
224
225
            // Get the form field values
226
            $data = $form->getData();
227
228
            $updatedObject = $this->getService()->updateFromArray($data, $this->getCurrentEditionLocale());
229
230
            // Check if object exist
231
            if (!$updatedObject) {
232
                throw new \LogicException(
233
                    $this->getTranslator()->trans("No %obj was updated.", ['%obj' => static::CONTROLLER_ENTITY_NAME])
234
                );
235
            }
236
237
            $con->commit();
238
            // If we have to stay on the same page, do not redirect to the successUrl,
239
            // just redirect to the edit page again.
240
            if ($this->getRequest()->get('save_mode') == 'stay') {
241
                return $this->redirectToEditionTemplate($this->getRequest());
242
            }
243
244
            // Redirect to the success URL
245
            return $this->generateSuccessRedirect($changeForm);
246
        } catch (FormValidationException $ex) {
0 ignored issues
show
Bug introduced by
The class Thelia\Form\Exception\FormValidationException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
247
            $con->rollBack();
248
            // Form cannot be validated
249
            $error_msg = $this->createStandardFormValidationErrorMessage($ex);
250
        } catch (\Exception $ex) {
251
            $con->rollBack();
252
            // Any other error
253
            $error_msg = $ex->getMessage();
254
        }
255
256
        if (false !== $error_msg) {
257
            // At this point, the form has errors, and should be redisplayed.
258
            $this->setupFormErrorContext(
259
                $this->getTranslator()->trans("%obj modification", ['%obj' => static::CONTROLLER_ENTITY_NAME]),
260
                $error_msg,
261
                $changeForm,
262
                $ex
263
            );
264
265
            return $this->getEditRenderTemplate();
266
        }
267
    }
268
269
    /**
270
     * Delete an object
271
     *
272
     * @return \Thelia\Core\HttpFoundation\Response the response
273
     */
274
    public function deleteAction()
275
    {
276
        // Check current user authorization
277
        if (null !== $response = $this->checkAuth(static::CONTROLLER_CHECK_RESOURCE, Dealer::getModuleCode(),
278
                AccessManager::DELETE)
279
        ) {
280
            return $response;
281
        }
282
283
        $con = Propel::getConnection();
284
        $con->beginTransaction();
285
        try {
286
            // Check token
287
            $this->getTokenProvider()->checkToken(
288
                $this->getRequest()->query->get("_token")
289
            );
290
291
            $this->getService()->deleteFromId($this->getRequest()->request->get(static::CONTROLLER_ENTITY_NAME . "_id"));
292
            $con->commit();
293
            if ($this->getRequest()->request->get("success_url") == null) {
294
                return $this->redirectToListTemplate();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->redirectToListTemplate(); (Symfony\Component\HttpFoundation\RedirectResponse) is incompatible with the return type documented by Dealer\Controller\Base\B...ontroller::deleteAction of type Thelia\Core\HttpFoundation\Response.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
295
            } else {
296
                return new RedirectResponse(URL::getInstance()->absoluteUrl($this->getRequest()->request->get("success_url")));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Symfony\Comp...->get('success_url'))); (Symfony\Component\HttpFoundation\RedirectResponse) is incompatible with the return type documented by Dealer\Controller\Base\B...ontroller::deleteAction of type Thelia\Core\HttpFoundation\Response.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
297
            }
298
        } catch (\Exception $e) {
299
            $con->rollBack();
300
301
            return $this->renderAfterDeleteError($e);
302
        }
303
    }
304
305
    // HELPERS
306
    /**
307
     * Method to get current controller associated service
308
     * @return object
309
     */
310
    protected function getService()
311
    {
312
        if (!$this->service) {
313
            $this->service = $this->getContainer()->get(static::CONTROLLER_ENTITY_NAME . "_service");
314
        }
315
316
        return $this->service;
317
    }
318
319
    /**
320
     * Method to get Base Creation Form
321
     * @return \Thelia\Form\BaseForm
322
     */
323
    protected function getCreationForm()
324
    {
325
        return $this->createForm(static::CONTROLLER_ENTITY_NAME . ".create");
326
    }
327
328
    /**
329
     * Method to get Base Update Form
330
     * @param array $data
331
     * @return \Thelia\Form\BaseForm
332
     */
333
    protected function getUpdateForm($data = [])
334
    {
335
        if (!is_array($data)) {
336
            $data = [];
337
        }
338
339
        return $this->createForm(static::CONTROLLER_ENTITY_NAME . ".update", "form", $data);
340
    }
341
342
    /**
343
     * @param \Exception $e
344
     * @return \Thelia\Core\HttpFoundation\Response
345
     */
346
    protected function renderAfterDeleteError(\Exception $e)
347
    {
348
        $errorMessage = sprintf(
349
            "Unable to delete '%s'. Error message: %s",
350
            static::CONTROLLER_ENTITY_NAME,
351
            $e->getMessage()
352
        );
353
354
        $this->getParserContext()
355
            ->setGeneralError($errorMessage);
356
357
        return $this->defaultAction();
358
    }
359
360
    protected function checkUserAccessDealer($id = null)
361
    {
362
        $admin = $this->getSecurityContext()->getAdminUser();
363
        if (in_array("SUPERADMIN", $admin->getRoles())) {
364
            return null;
365
        }
366
367
        $dealers = DealerQuery::create()->filterById($id)->useDealerAdminQuery()->filterByAdminId($admin->getId())->endUse()->find();
368
369
        if (count($dealers) > 0) {
370
            return null;
371
        }
372
373
        return $this->errorPage($this->getTranslator()->trans("Sorry, you're not allowed to perform this action"), 403);
374
    }
375
376
    protected function getAdminDealer()
377
    {
378
        $admin = $this->getSecurityContext()->getAdminUser();
379
380
        if ($admin === null) {
381
            return null;
382
        }
383
384
        if (in_array("SUPERADMIN", $admin->getRoles())) {
385
            return DealerQuery::create()->find();
386
        }
387
388
        return DealerQuery::create()->useDealerAdminQuery()->filterByAdminId($admin->getId())->endUse()->find();
389
    }
390
}
391