Completed
Push — feature/model-restoration ( 71d832 )
by Vladimir
02:38
created

CRUDController   B

Complexity

Total Complexity 37

Size/Duplication

Total Lines 386
Duplicated Lines 7.25 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 0
Metric Value
wmc 37
lcom 1
cbo 12
dl 28
loc 386
rs 8.6
c 0
b 0
f 0

15 Methods

Rating   Name   Duplication   Size   Complexity  
A validateNew() 0 3 1
A validateEdit() 0 3 1
A validate() 0 3 1
B delete() 16 37 6
B restore() 12 27 5
B create() 0 30 6
B edit() 0 23 4
A canDelete() 0 4 1
A canCreate() 0 6 1
A canEdit() 0 4 1
A redirectTo() 0 8 2
A redirectToList() 0 7 1
A getFormCreator() 0 10 2
B getMessage() 0 26 4
A getMessages() 0 73 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
use BZIon\Form\Creator\ModelFormCreator;
4
use Symfony\Component\Form\Form;
5
use Symfony\Component\HttpFoundation\RedirectResponse;
6
use Symfony\Component\HttpFoundation\Response;
7
8
/**
9
 * A controller with actions for creating, reading, updating and deleting models
10
 * @package BZiON\Controllers
11
 */
12
abstract class CRUDController extends JSONController
13
{
14
    /**
15
     * Make sure that the data of a form is valid, only called when creating a
16
     * new object
17
     * @param  Form $form The submitted form
18
     * @return void
19
     */
20
    protected function validateNew($form)
21
    {
22
    }
23
24
    /**
25
     * Make sure that the data of a form is valid, only called when editing an
26
     * existing object
27
     * @param  Form $form The submitted form
28
     * @param  PermissionModel $model The model being edited
29
     * @return void
30
     */
31
    protected function validateEdit($form, $model)
32
    {
33
    }
34
35
    /**
36
     * Make sure that the data of a form is valid
37
     * @param  Form $form The submitted form
38
     * @return void
39
     */
40
    protected function validate($form)
41
    {
42
    }
43
44
    /**
45
     * Delete a model
46
     * @param  PermissionModel    $model     The model we want to delete
47
     * @param  Player             $me        The user who wants to delete the model
48
     * @param  Closure|null       $onSuccess Something to do when the model is deleted
49
     * @throws ForbiddenException
50
     * @return mixed              The response to show to the user
51
     */
52
    protected function delete(PermissionModel $model, Player $me, $onSuccess = null)
53
    {
54
        if ($model->isDeleted()) {
55
            // We will have to hard delete the model
56
            $hard = true;
57
            $message = 'hardDelete';
58
            $action = 'Erase forever';
59
        } else {
60
            $hard = false;
61
            $message = 'softDelete';
62
            $action = 'Delete';
63
        }
64
65
        if (!$this->canDelete($me, $model, $hard)) {
66
            throw new ForbiddenException($this->getMessage($model, $message, 'forbidden'));
67
        }
68
69
        $successMessage = $this->getMessage($model, $message, 'success');
70
        $redirection    = $this->redirectToList($model);
71
72 View Code Duplication
        return $this->showConfirmationForm(function () use ($model, $hard, $redirection, $onSuccess) {
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...
73
            if ($hard) {
74
                $model->wipe();
75
            } else {
76
                $model->delete();
77
            }
78
79
            if ($onSuccess) {
80
                $response = $onSuccess();
81
                if ($response instanceof Response) {
82
                    return $response;
83
                }
84
            }
85
86
            return $redirection;
87
        }, $this->getMessage($model, $message, 'confirm'), $successMessage, $action);
88
    }
89
90
    protected function restore(PermissionModel $model, Player $me, $onSuccess)
91
    {
92
        if (!$this->canDelete($me, $model))
93
        {
94
            throw new ForbiddenException($this->getMessage($model, 'restore', 'forbidden'));
95
        }
96
97
        if (!$model->isDeleted())
98
        {
99
            throw new LogicException('You cannot restore an object that is not marked as deleted.');
100
        }
101
102
        $successMessage = $this->getMessage($model, 'restore', 'success');
103
104 View Code Duplication
        return $this->showConfirmationForm(function () use ($model, $successMessage, $onSuccess) {
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...
105
            $model->restore();
106
107
            if ($onSuccess) {
108
                $response = $onSuccess();
109
                if ($response instanceof Response) {
110
                    return $response;
111
                }
112
            }
113
114
            return $this->redirectTo($model);
115
        }, $this->getMessage($model, 'restore', 'confirm'), $successMessage, 'Restore');
116
    }
117
118
    /**
119
     * Create a model
120
     *
121
     * This method requires that you have implemented enter() and a form creator
122
     * for the model
123
     *
124
     * @param  Player             $me The user who wants to create the model
125
     * @param  Closure|null       $onSuccess The function to call on success
126
     * @throws ForbiddenException
127
     * @return mixed              The response to show to the user
128
     */
129
    protected function create(Player $me, $onSuccess = null)
130
    {
131
        if (!$this->canCreate($me)) {
132
            throw new ForbiddenException($this->getMessage($this->getName(), 'create', 'forbidden'));
133
        }
134
135
        $creator = $this->getFormCreator();
136
        $form = $creator->create()->handleRequest($this->getRequest());
137
138
        if ($form->isSubmitted()) {
139
            $this->validate($form);
140
            $this->validateNew($form);
141
            if ($form->isValid()) {
142
                $model = $creator->enter($form);
143
                $this->getFlashBag()->add("success",
144
                     $this->getMessage($model, 'create', 'success'));
145
146
                if ($onSuccess) {
147
                    $response = $onSuccess($model);
148
                    if ($response instanceof Response) {
149
                        return $response;
150
                    }
151
                }
152
153
                return $this->redirectTo($model);
154
            }
155
        }
156
157
        return array("form" => $form->createView());
158
    }
159
160
    /**
161
     * Edit a model
162
     *
163
     * This method requires that you have implemented update() and a form creator
164
     * for the model
165
     *
166
     * @param  PermissionModel    $model The model we want to edit
167
     * @param  Player             $me    The user who wants to edit the model
168
     * @param  string             $type  The name of the variable to pass to the view
169
     * @throws ForbiddenException
170
     * @return mixed              The response to show to the user
171
     */
172
    protected function edit(PermissionModel $model, Player $me, $type)
173
    {
174
        if (!$this->canEdit($me, $model)) {
175
            throw new ForbiddenException($this->getMessage($model, 'edit', 'forbidden'));
176
        }
177
178
        $creator = $this->getFormCreator($model);
179
        $form = $creator->create()->handleRequest($this->getRequest());
180
181
        if ($form->isSubmitted()) {
182
            $this->validate($form);
183
            $this->validateEdit($form, $model);
184
            if ($form->isValid()) {
185
                $creator->update($form, $model);
186
                $this->getFlashBag()->add("success",
187
                    $this->getMessage($model, 'edit', 'success'));
188
189
                return $this->redirectTo($model);
190
            }
191
        }
192
193
        return array("form" => $form->createView(), $type => $model);
194
    }
195
196
    /**
197
     * Find whether a player can delete a model
198
     *
199
     * @param  Player          $player The player who wants to delete the model
200
     * @param  PermissionModel $model  The model that will be deleted
201
     * @param  bool         $hard   Whether to hard-delete the model instead of soft-deleting it
202
     * @return bool
203
     */
204
    protected function canDelete($player, $model, $hard = false)
205
    {
206
        return $player->canDelete($model, $hard);
207
    }
208
209
    /**
210
     * Find whether a player can create a model
211
     *
212
     * @param  Player  $player The player who wants to create a model
213
     * @return bool
214
     */
215
    protected function canCreate($player)
216
    {
217
        $modelName = $this->getName();
218
219
        return $player->canCreate($modelName);
220
    }
221
222
    /**
223
     * Find whether a player can edit a model
224
     *
225
     * @param  Player          $player The player who wants to delete the model
226
     * @param  PermissionModel $model  The model which will be edited
227
     * @return bool
228
     */
229
    protected function canEdit($player, $model)
230
    {
231
        return $player->canEdit($model);
232
    }
233
234
    /**
235
     * Get a redirection response to a model
236
     *
237
     * Goes to a list of models of the same type if the provided model does not
238
     * have a URL
239
     *
240
     * @param  ModelInterface $model The model to redirect to
241
     * @return Response
242
     */
243
    protected function redirectTo($model)
244
    {
245
        if ($model instanceof UrlModel) {
246
            return new RedirectResponse($model->getUrl());
247
        } else {
248
            return $this->redirectToList($model);
249
        }
250
    }
251
252
    /**
253
     * Get a redirection response to a list of models
254
     *
255
     * @param  ModelInterface $model The model to whose list we should redirect
256
     * @return Response
257
     */
258
    protected function redirectToList($model)
259
    {
260
        $route = $model->getRouteName('list');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface ModelInterface as the method getRouteName() does only exist in the following implementations of said interface: AliasModel, AvatarModel, Ban, Conversation, Invitation, Map, Match, News, NewsCategory, Page, Player, Role, Server, Team, UrlModel.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
261
        $url = Service::getGenerator()->generate($route);
262
263
        return new RedirectResponse($url);
264
    }
265
266
    /**
267
     * Dynamically get the form to show to the user
268
     *
269
     * @param  \Model|null      $model The model being edited, `null` if we're creating one
270
     * @return ModelFormCreator
271
     */
272
    private function getFormCreator($model = null)
273
    {
274
        $type = ($model instanceof Model) ? $model->getType() : $this->getName();
275
        $type = ucfirst($type);
276
277
        $creatorClass = "\\BZIon\\Form\\Creator\\{$type}FormCreator";
278
        $creator = new $creatorClass($model, $this->getMe(), $this);
279
280
        return $creator;
281
    }
282
283
    /**
284
     * Get a message to show to the user
285
     * @todo   Use the $escape parameter
286
     * @param  \ModelInterface|string $model  The model (or type) to show a message for
287
     * @param  string                 $action The action that will be performed (softDelete, hardDelete, create or edit)
288
     * @param  string                 $status The message's status (confirm, error or success)
289
     * @return string
290
     */
291
    private function getMessage($model, $action, $status, $escape = true)
0 ignored issues
show
Unused Code introduced by
The parameter $escape 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...
292
    {
293
        if ($model instanceof Model) {
294
            $type = strtolower($model->getTypeForHumans());
295
296
            if ($model instanceof NamedModel) {
297
                // Twig will not escape the message on confirmation forms
298
                $name = $model->getName();
299
                if ($status == 'confirm') {
300
                    $name = Model::escape($name);
301
                }
302
303
                $messages = $this->getMessages($type, $name);
304
305
                return $messages[$action][$status]['named'];
306
            } else {
307
                $messages = $this->getMessages($type);
308
309
                return $messages[$action][$status]['unnamed'];
310
            }
311
        } else {
312
            $messages = $this->getMessages(strtolower($model));
313
314
            return $messages[$action][$status];
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $messages[$action][$status]; (array) is incompatible with the return type documented by CRUDController::getMessage of type string.

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...
315
        }
316
    }
317
318
    /**
319
     * Get a list of messages to show to the user
320
     * @param  string $type The type of the model that the message refers to
321
     * @param  string $name The name of the model
322
     * @return array
323
     */
324
    protected function getMessages($type, $name = '')
325
    {
326
        return array(
327
            'hardDelete' => array(
328
                'confirm' => array(
329
                    'named' => <<<"WARNING"
330
Are you sure you want to wipe <strong>$name</strong>?<br />
331
<strong><em>DANGER</em></strong>: This action will <strong>permanently</strong>
332
erase the $type from the database, including any objects directly related to it!
333
WARNING
334
                ,
335
                    'unnamed' => <<<"WARNING"
336
Are you sure you want to wipe this $type?<br />
337
<strong><em>DANGER</em></strong>: This action will <strong>permanently</strong>
338
erase the $type from the database, including any objects directly related to it!
339
WARNING
340
                ),
341
                'forbidden' => array(
342
                    'named'   => "You are not allowed to delete the $type $name",
343
                    'unnamed' => "You are not allowed to delete this $type",
344
                ),
345
                'success' => array(
346
                    'named'   => "The $type $name was permanently erased from the database",
347
                    'unnamed' => "The $type has been permanently erased from the database",
348
                ),
349
            ),
350
            'softDelete' => array(
351
                'confirm' => array(
352
                    'named'   => "Are you sure you want to delete <strong>$name</strong>?",
353
                    'unnamed' => "Are you sure you want to delete this $type?",
354
                ),
355
                'forbidden' => array(
356
                    'named'   => "You are not allowed to delete the $type $name",
357
                    'unnamed' => "You are not allowed to delete this $type",
358
                ),
359
                'success' => array(
360
                    'named'   => "The $type $name was deleted successfully",
361
                    'unnamed' => "The $type was deleted successfully",
362
                ),
363
            ),
364
            'restore' => array(
365
                'confirm' => array(
366
                    'named'   => "Are you sure you want to restore <strong>$name</strong>?",
367
                    'unnamed' => "Are you sure you want to restore this $type?",
368
                ),
369
                'forbidden' => array(
370
                    'named'   => "You are not allowed to restore the $type $name",
371
                    'unnamed' => "You are not allowed to restore this $type",
372
                ),
373
                'success' => array(
374
                    'named'   => "The $type $name has been restored successfully",
375
                    'unnamed' => "The $type has been restored successfully",
376
                ),
377
            ),
378
            'edit' => array(
379
                'forbidden' => array(
380
                    'named'   => "You are not allowed to edit the $type $name",
381
                    'unnamed' => "You are not allowed to edit this $type",
382
                ),
383
                'success' => array(
384
                    'named'   => "The $type $name has been successfully updated",
385
                    'unnamed' => "The $type was updated successfully",
386
                ),
387
            ),
388
            'create' => array(
389
                'forbidden' => "You are not allowed to create a new $type",
390
                'success'   => array(
391
                    'named'   => "The $type $name was created successfully",
392
                    'unnamed' => "The $type was created successfully",
393
                ),
394
            ),
395
        );
396
    }
397
}
398