Completed
Push — master ( 3eac5a...b98009 )
by Vladimir
04:57
created

src/Controller/CRUDController.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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 1
    protected function validateNew($form)
21
    {
22 1
    }
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 1
    protected function delete(PermissionModel $model, Player $me, $onSuccess = null)
53
    {
54 1
        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 1
            $hard = false;
61 1
            $message = 'softDelete';
62 1
            $action = 'Delete';
63
        }
64
65 1
        if (!$this->canDelete($me, $model, $hard)) {
66
            throw new ForbiddenException($this->getMessage($model, $message, 'forbidden'));
67
        }
68
69 1
        $successMessage = $this->getMessage($model, $message, 'success');
70 1
        $redirection    = $this->redirectToList($model);
71
72 1 View Code Duplication
        return $this->showConfirmationForm(function () use ($model, $hard, $redirection, $onSuccess) {
0 ignored issues
show
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 1
            if ($hard) {
74
                $model->wipe();
75
            } else {
76 1
                $model->delete();
77
            }
78
79 1
            if ($onSuccess) {
80 1
                $response = $onSuccess();
81 1
                if ($response instanceof Response) {
82
                    return $response;
83
                }
84
            }
85
86 1
            return $redirection;
87 1
        }, $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
            throw new ForbiddenException($this->getMessage($model, 'restore', 'forbidden'));
94
        }
95
96
        if (!$model->isDeleted()) {
97
            throw new LogicException('You cannot restore an object that is not marked as deleted.');
98
        }
99
100
        $successMessage = $this->getMessage($model, 'restore', 'success');
101 1
102 View Code Duplication
        return $this->showConfirmationForm(function () use ($model, $successMessage, $onSuccess) {
103 1
            $model->restore();
104 1
105
            if ($onSuccess) {
106
                $response = $onSuccess();
107 1
                if ($response instanceof Response) {
108 1
                    return $response;
109
                }
110 1
            }
111 1
112 1
            return $this->redirectTo($model);
113 1
        }, $this->getMessage($model, 'restore', 'confirm'), $successMessage, 'Restore');
114 1
    }
115 1
116 1
    /**
117
     * Create a model
118 1
     *
119 1
     * This method requires that you have implemented enter() and a form creator
120 1
     * for the model
121
     *
122
     * @param  Player             $me The user who wants to create the model
123
     * @param  Closure|null       $onSuccess The function to call on success
124
     * @throws ForbiddenException
125 1
     * @return mixed              The response to show to the user
126
     */
127
    protected function create(Player $me, $onSuccess = null)
128
    {
129 1
        if (!$this->canCreate($me)) {
130
            throw new ForbiddenException($this->getMessage($this->getName(), 'create', 'forbidden'));
131
        }
132
133
        $creator = $this->getFormCreator();
134
        $form = $creator->create()->handleRequest($this->getRequest());
135
136
        if ($form->isSubmitted()) {
137
            $this->validate($form);
138
            $this->validateNew($form);
139
            if ($form->isValid()) {
140
                $model = $creator->enter($form);
141
                $this->getFlashBag()->add("success",
142
                     $this->getMessage($model, 'create', 'success'));
143
144
                if ($onSuccess) {
145
                    $response = $onSuccess($model);
146
                    if ($response instanceof Response) {
147
                        return $response;
148
                    }
149
                }
150
151
                return $this->redirectTo($model);
152
            }
153
        }
154
155
        return array("form" => $form->createView());
156
    }
157
158
    /**
159
     * Edit a model
160
     *
161
     * This method requires that you have implemented update() and a form creator
162
     * for the model
163
     *
164
     * @param  PermissionModel    $model The model we want to edit
165
     * @param  Player             $me    The user who wants to edit the model
166
     * @param  string             $type  The name of the variable to pass to the view
167
     * @throws ForbiddenException
168
     * @return mixed              The response to show to the user
169
     */
170
    protected function edit(PermissionModel $model, Player $me, $type)
171
    {
172
        if (!$this->canEdit($me, $model)) {
173
            throw new ForbiddenException($this->getMessage($model, 'edit', 'forbidden'));
174
        }
175
176 1
        $creator = $this->getFormCreator($model);
177
        $form = $creator->create()->handleRequest($this->getRequest());
178 1
179
        if ($form->isSubmitted()) {
180
            $this->validate($form);
181
            $this->validateEdit($form, $model);
182
            if ($form->isValid()) {
183
                $creator->update($form, $model);
184
                $this->getFlashBag()->add("success",
185
                    $this->getMessage($model, 'edit', 'success'));
186
187 1
                return $this->redirectTo($model);
188
            }
189 1
        }
190
191 1
        return array("form" => $form->createView(), $type => $model);
192
    }
193
194
    /**
195
     * Find whether a player can delete a model
196
     *
197
     * @param  Player          $player The player who wants to delete the model
198
     * @param  PermissionModel $model  The model that will be deleted
199
     * @param  bool         $hard   Whether to hard-delete the model instead of soft-deleting it
200
     * @return bool
201
     */
202
    protected function canDelete($player, $model, $hard = false)
203
    {
204
        return $player->canDelete($model, $hard);
205
    }
206
207
    /**
208
     * Find whether a player can create a model
209
     *
210
     * @param  Player  $player The player who wants to create a model
211
     * @return bool
212
     */
213
    protected function canCreate($player)
214
    {
215 1
        $modelName = $this->getName();
216
217 1
        return $player->canCreate($modelName);
218 1
    }
219
220
    /**
221
     * Find whether a player can edit a model
222
     *
223
     * @param  Player          $player The player who wants to delete the model
224
     * @param  PermissionModel $model  The model which will be edited
225
     * @return bool
226
     */
227
    protected function canEdit($player, $model)
228
    {
229
        return $player->canEdit($model);
230 1
    }
231
232 1
    /**
233 1
     * Get a redirection response to a model
234
     *
235 1
     * Goes to a list of models of the same type if the provided model does not
236
     * have a URL
237
     *
238
     * @param  ModelInterface $model The model to redirect to
239
     * @return Response
240
     */
241
    protected function redirectTo($model)
242
    {
243
        if ($model instanceof UrlModel) {
244 1
            return new RedirectResponse($model->getUrl());
245
        } else {
246 1
            return $this->redirectToList($model);
247 1
        }
248
    }
249 1
250 1
    /**
251
     * Get a redirection response to a list of models
252 1
     *
253
     * @param  ModelInterface $model The model to whose list we should redirect
254
     * @return Response
255
     */
256
    protected function redirectToList($model)
257
    {
258
        $route = $model->getRouteName('list');
259
        $url = Service::getGenerator()->generate($route);
260
261
        return new RedirectResponse($url);
262
    }
263 1
264
    /**
265 1
     * Dynamically get the form to show to the user
266 1
     *
267
     * @param  \Model|null      $model The model being edited, `null` if we're creating one
268 1
     * @return ModelFormCreator
269
     */
270 1
    private function getFormCreator($model = null)
271 1
    {
272 1
        $type = ($model instanceof Model) ? $model->getType() : $this->getName();
273
        $type = ucfirst($type);
274
275 1
        $creatorClass = "\\BZIon\\Form\\Creator\\{$type}FormCreator";
276
        $creator = new $creatorClass($model, $this->getMe(), $this);
277 1
278
        return $creator;
279
    }
280
281
    /**
282
     * Get a message to show to the user
283
     * @todo   Use the $escape parameter
284 1
     * @param  \ModelInterface|string $model  The model (or type) to show a message for
285
     * @param  string                 $action The action that will be performed (softDelete, hardDelete, create or edit)
286 1
     * @param  string                 $status The message's status (confirm, error or success)
287
     * @return string
288
     */
289
    private function getMessage($model, $action, $status, $escape = true)
290
    {
291
        if ($model instanceof Model) {
292
            $type = strtolower($model->getTypeForHumans());
293
294
            if ($model instanceof NamedModel) {
295
                // Twig will not escape the message on confirmation forms
296 1
                $name = $model->getName();
297
                if ($status == 'confirm') {
298
                    $name = Model::escape($name);
299
                }
300
301
                $messages = $this->getMessages($type, $name);
302 1
303
                return $messages[$action][$status]['named'];
304 1
            } else {
305
                $messages = $this->getMessages($type);
306
307
                return $messages[$action][$status]['unnamed'];
308 1
            }
309
        } else {
310 1
            $messages = $this->getMessages(strtolower($model));
311
312
            return $messages[$action][$status];
313
        }
314 1
    }
315 1
316
    /**
317
     * Get a list of messages to show to the user
318 1
     * @param  string $type The type of the model that the message refers to
319 1
     * @param  string $name The name of the model
320
     * @return array
321
     */
322
    protected function getMessages($type, $name = '')
323
    {
324 1
        return array(
325 1
            'hardDelete' => array(
326
                'confirm' => array(
327
                    'named' => <<<"WARNING"
328 1
Are you sure you want to wipe <strong>$name</strong>?<br />
329 1
<strong><em>DANGER</em></strong>: This action will <strong>permanently</strong>
330
erase the $type from the database, including any objects directly related to it!
331
WARNING
332 1
                ,
333 1
                    'unnamed' => <<<"WARNING"
334
Are you sure you want to wipe this $type?<br />
335
<strong><em>DANGER</em></strong>: This action will <strong>permanently</strong>
336
erase the $type from the database, including any objects directly related to it!
337
WARNING
338 1
                ),
339 1
                'forbidden' => array(
340
                    'named'   => "You are not allowed to delete the $type $name",
341
                    'unnamed' => "You are not allowed to delete this $type",
342 1
                ),
343 1
                'success' => array(
344
                    'named'   => "The $type $name was permanently erased from the database",
345
                    'unnamed' => "The $type has been permanently erased from the database",
346
                ),
347 1
            ),
348
            'softDelete' => array(
349 1
                'confirm' => array(
350 1
                    'named'   => "Are you sure you want to delete <strong>$name</strong>?",
351
                    'unnamed' => "Are you sure you want to delete this $type?",
352
                ),
353
                'forbidden' => array(
354
                    'named'   => "You are not allowed to delete the $type $name",
355
                    'unnamed' => "You are not allowed to delete this $type",
356
                ),
357
                'success' => array(
358
                    'named'   => "The $type $name was deleted successfully",
359
                    'unnamed' => "The $type was deleted successfully",
360
                ),
361
            ),
362
            'restore' => array(
363
                'confirm' => array(
364
                    'named'   => "Are you sure you want to restore <strong>$name</strong>?",
365
                    'unnamed' => "Are you sure you want to restore this $type?",
366
                ),
367
                'forbidden' => array(
368
                    'named'   => "You are not allowed to restore the $type $name",
369
                    'unnamed' => "You are not allowed to restore this $type",
370
                ),
371
                'success' => array(
372
                    'named'   => "The $type $name has been restored successfully",
373
                    'unnamed' => "The $type has been restored successfully",
374
                ),
375
            ),
376
            'edit' => array(
377
                'forbidden' => array(
378
                    'named'   => "You are not allowed to edit the $type $name",
379
                    'unnamed' => "You are not allowed to edit this $type",
380
                ),
381
                'success' => array(
382
                    'named'   => "The $type $name has been successfully updated",
383
                    'unnamed' => "The $type was updated successfully",
384
                ),
385
            ),
386
            'create' => array(
387
                'forbidden' => "You are not allowed to create a new $type",
388
                'success'   => array(
389
                    'named'   => "The $type $name was created successfully",
390
                    'unnamed' => "The $type was created successfully",
391
                ),
392
            ),
393
        );
394
    }
395
}
396