Completed
Push — master ( 5247c6...b8f763 )
by Craig
10:35 queued 03:41
created

AbstractRouteController::adminDeleteAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Routes.
4
 *
5
 * @copyright Zikula contributors (Zikula)
6
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
7
 * @author Zikula contributors <[email protected]>.
8
 * @link http://www.zikula.org
9
 * @link http://zikula.org
10
 * @version Generated by ModuleStudio 0.7.1 (http://modulestudio.de).
11
 */
12
13
namespace Zikula\RoutesModule\Controller\Base;
14
15
use RuntimeException;
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
18
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
19
use Symfony\Component\HttpFoundation\RedirectResponse;
20
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
21
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
22
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
23
use Zikula\Component\SortableColumns\Column;
24
use Zikula\Component\SortableColumns\SortableColumns;
25
use Zikula\Core\Controller\AbstractController;
26
use Zikula\RoutesModule\Entity\RouteEntity;
27
28
/**
29
 * Route controller base class.
30
 */
31
abstract class AbstractRouteController extends AbstractController
32
{
33
    /**
34
     * This is the default action handling the main admin area called without defining arguments.
35
     * @Cache(expires="+7 days", public=true)
36
     *
37
     * @param Request $request Current request instance
38
     *
39
     * @return Response Output
40
     *
41
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
42
     */
43
    public function adminIndexAction(Request $request)
44
    {
45
        return $this->indexInternal($request, true);
46
    }
47
48
    /**
49
     * This is the default action handling the main area called without defining arguments.
50
     * @Cache(expires="+7 days", public=true)
51
     *
52
     * @param Request $request Current request instance
53
     *
54
     * @return Response Output
55
     *
56
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
57
     */
58
    public function indexAction(Request $request)
59
    {
60
        return $this->indexInternal($request, false);
61
    }
62
63
    /**
64
     * This method includes the common implementation code for adminIndex() and index().
65
     */
66
    protected function indexInternal(Request $request, $isAdmin = false)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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...
67
    {
68
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
0 ignored issues
show
Unused Code introduced by
$controllerHelper 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...
69
70
        // parameter specifying which type of objects we are treating
71
        $objectType = 'route';
72
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_OVERVIEW;
73
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', '::', $permLevel)) {
74
            throw new AccessDeniedException();
75
        }
76
        $templateParameters = [
77
            'routeArea' => $isAdmin ? 'admin' : ''
78
        ];
79
        
80
        return $this->redirectToRoute('zikularoutesmodule_route_' . $templateParameters['routeArea'] . 'view');
81
        
82
        // return index template
83
        return $this->render('@ZikulaRoutesModule/Route/index.html.twig', $templateParameters);
0 ignored issues
show
Unused Code introduced by
// return index template..., $templateParameters); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
84
    }
85
    /**
86
     * This action provides an item list overview in the admin area.
87
     * @Cache(expires="+2 hours", public=false)
88
     *
89
     * @param Request $request Current request instance
90
     * @param string $sort         Sorting field
91
     * @param string $sortdir      Sorting direction
92
     * @param int    $pos          Current pager position
93
     * @param int    $num          Amount of entries to display
94
     *
95
     * @return Response Output
96
     *
97
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
98
     */
99
    public function adminViewAction(Request $request, $sort, $sortdir, $pos, $num)
100
    {
101
        return $this->viewInternal($request, $sort, $sortdir, $pos, $num, true);
102
    }
103
104
    /**
105
     * This action provides an item list overview.
106
     * @Cache(expires="+2 hours", public=false)
107
     *
108
     * @param Request $request Current request instance
109
     * @param string $sort         Sorting field
110
     * @param string $sortdir      Sorting direction
111
     * @param int    $pos          Current pager position
112
     * @param int    $num          Amount of entries to display
113
     *
114
     * @return Response Output
115
     *
116
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
117
     */
118
    public function viewAction(Request $request, $sort, $sortdir, $pos, $num)
119
    {
120
        return $this->viewInternal($request, $sort, $sortdir, $pos, $num, false);
121
    }
122
123
    /**
124
     * This method includes the common implementation code for adminView() and view().
125
     */
126
    protected function viewInternal(Request $request, $sort, $sortdir, $pos, $num, $isAdmin = false)
0 ignored issues
show
Unused Code introduced by
The parameter $pos 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...
Unused Code introduced by
The parameter $num 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...
127
    {
128
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
0 ignored issues
show
Unused Code introduced by
$controllerHelper 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...
129
130
        // parameter specifying which type of objects we are treating
131
        $objectType = 'route';
132
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_READ;
133
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', '::', $permLevel)) {
134
            throw new AccessDeniedException();
135
        }
136
        $templateParameters = [
137
            'routeArea' => $isAdmin ? 'admin' : ''
138
        ];
139
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
140
        $viewHelper = $this->get('zikula_routes_module.view_helper');
141
        
142
        // parameter for used sort order
143
        $sortdir = strtolower($sortdir);
144
        $request->query->set('sort', $sort);
145
        $request->query->set('sortdir', $sortdir);
146
        
147
        $sortableColumns = new SortableColumns($this->get('router'), 'zikularoutesmodule_route_' . ($isAdmin ? 'admin' : '') . 'view', 'sort', 'sortdir');
148
        $sortableColumns->addColumns([
149
            new Column('routeType'),
150
            new Column('replacedRouteName'),
151
            new Column('bundle'),
152
            new Column('controller'),
153
            new Column('action'),
154
            new Column('path'),
155
            new Column('host'),
156
            new Column('schemes'),
157
            new Column('methods'),
158
            new Column('prependBundlePrefix'),
159
            new Column('translatable'),
160
            new Column('translationPrefix'),
161
            new Column('condition'),
162
            new Column('description'),
163
            new Column('sort'),
164
            new Column('group'),
165
            new Column('createdBy'),
166
            new Column('createdDate'),
167
            new Column('updatedBy'),
168
            new Column('updatedDate'),
169
        ]);
170
        
171
        $templateParameters = $controllerHelper->processViewActionParameters($objectType, $sortableColumns, $templateParameters);
172
        
173
        foreach ($templateParameters['items'] as $k => $entity) {
174
            $entity->initWorkflow();
175
        }
176
        
177
        // fetch and return the appropriate template
178
        return $viewHelper->processTemplate($objectType, 'view', $templateParameters);
179
    }
180
    /**
181
     * This action provides a item detail view in the admin area.
182
     * @ParamConverter("route", class="ZikulaRoutesModule:RouteEntity", options={"id" = "id", "repository_method" = "selectById"})
183
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
184
     *
185
     * @param Request $request Current request instance
186
     * @param RouteEntity $route Treated route instance
187
     *
188
     * @return Response Output
189
     *
190
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
191
     * @throws NotFoundHttpException Thrown by param converter if item to be displayed isn't found
192
     */
193
    public function adminDisplayAction(Request $request, RouteEntity $route)
194
    {
195
        return $this->displayInternal($request, $route, true);
196
    }
197
198
    /**
199
     * This action provides a item detail view.
200
     * @ParamConverter("route", class="ZikulaRoutesModule:RouteEntity", options={"id" = "id", "repository_method" = "selectById"})
201
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
202
     *
203
     * @param Request $request Current request instance
204
     * @param RouteEntity $route Treated route instance
205
     *
206
     * @return Response Output
207
     *
208
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
209
     * @throws NotFoundHttpException Thrown by param converter if item to be displayed isn't found
210
     */
211
    public function displayAction(Request $request, RouteEntity $route)
212
    {
213
        return $this->displayInternal($request, $route, false);
214
    }
215
216
    /**
217
     * This method includes the common implementation code for adminDisplay() and display().
218
     */
219
    protected function displayInternal(Request $request, RouteEntity $route, $isAdmin = false)
220
    {
221
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
0 ignored issues
show
Unused Code introduced by
$controllerHelper 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...
222
223
        // parameter specifying which type of objects we are treating
224
        $objectType = 'route';
225
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_READ;
226
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', '::', $permLevel)) {
227
            throw new AccessDeniedException();
228
        }
229
        // create identifier for permission check
230
        $instanceId = $route->createCompositeIdentifier();
231
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', $instanceId . '::', $permLevel)) {
232
            throw new AccessDeniedException();
233
        }
234
        
235
        $route->initWorkflow();
236
        $templateParameters = [
237
            'routeArea' => $isAdmin ? 'admin' : '',
238
            $objectType => $route
239
        ];
240
        
241
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
242
        $templateParameters = $controllerHelper->processDisplayActionParameters($objectType, $templateParameters);
243
        
244
        // fetch and return the appropriate template
245
        $response = $this->get('zikula_routes_module.view_helper')->processTemplate($objectType, 'display', $templateParameters);
246
        
247
        $format = $request->getRequestFormat();
248
        if ($format == 'ics') {
249
            $fileName = $objectType . '_' . (property_exists($route, 'slug') ? $route['slug'] : $route->getTitleFromDisplayPattern()) . '.ics';
250
            $response->headers->set('Content-Disposition', 'attachment; filename=' . $fileName);
251
        }
252
253
        return $response;
254
    }
255
    /**
256
     * This action provides a handling of edit requests in the admin area.
257
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
258
     *
259
     * @param Request $request Current request instance
260
     *
261
     * @return Response Output
262
     *
263
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
264
     * @throws NotFoundHttpException Thrown by form handler if item to be edited isn't found
265
     * @throws RuntimeException      Thrown if another critical error occurs (e.g. workflow actions not available)
266
     */
267
    public function adminEditAction(Request $request)
268
    {
269
        return $this->editInternal($request, true);
270
    }
271
272
    /**
273
     * This action provides a handling of edit requests.
274
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
275
     *
276
     * @param Request $request Current request instance
277
     *
278
     * @return Response Output
279
     *
280
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
281
     * @throws NotFoundHttpException Thrown by form handler if item to be edited isn't found
282
     * @throws RuntimeException      Thrown if another critical error occurs (e.g. workflow actions not available)
283
     */
284
    public function editAction(Request $request)
285
    {
286
        return $this->editInternal($request, false);
287
    }
288
289
    /**
290
     * This method includes the common implementation code for adminEdit() and edit().
291
     */
292
    protected function editInternal(Request $request, $isAdmin = false)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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...
293
    {
294
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
0 ignored issues
show
Unused Code introduced by
$controllerHelper 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...
295
296
        // parameter specifying which type of objects we are treating
297
        $objectType = 'route';
298
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_EDIT;
299
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', '::', $permLevel)) {
300
            throw new AccessDeniedException();
301
        }
302
        $templateParameters = [
303
            'routeArea' => $isAdmin ? 'admin' : ''
304
        ];
305
        
306
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
307
        $templateParameters = $controllerHelper->processEditActionParameters($objectType, $templateParameters);
308
        
309
        // delegate form processing to the form handler
310
        $formHandler = $this->get('zikula_routes_module.form.handler.route');
311
        $result = $formHandler->processForm($templateParameters);
312
        if ($result instanceof RedirectResponse) {
313
            return $result;
314
        }
315
        
316
        $templateParameters = $formHandler->getTemplateParameters();
317
318
        // fetch and return the appropriate template
319
        return $this->get('zikula_routes_module.view_helper')->processTemplate($objectType, 'edit', $templateParameters);
320
    }
321
    /**
322
     * This action provides a handling of simple delete requests in the admin area.
323
     * @ParamConverter("route", class="ZikulaRoutesModule:RouteEntity", options={"id" = "id", "repository_method" = "selectById"})
324
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
325
     *
326
     * @param Request $request Current request instance
327
     * @param RouteEntity $route Treated route instance
328
     *
329
     * @return Response Output
330
     *
331
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
332
     * @throws NotFoundHttpException Thrown by param converter if item to be deleted isn't found
333
     * @throws RuntimeException      Thrown if another critical error occurs (e.g. workflow actions not available)
334
     */
335
    public function adminDeleteAction(Request $request, RouteEntity $route)
336
    {
337
        return $this->deleteInternal($request, $route, true);
338
    }
339
340
    /**
341
     * This action provides a handling of simple delete requests.
342
     * @ParamConverter("route", class="ZikulaRoutesModule:RouteEntity", options={"id" = "id", "repository_method" = "selectById"})
343
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
344
     *
345
     * @param Request $request Current request instance
346
     * @param RouteEntity $route Treated route instance
347
     *
348
     * @return Response Output
349
     *
350
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
351
     * @throws NotFoundHttpException Thrown by param converter if item to be deleted isn't found
352
     * @throws RuntimeException      Thrown if another critical error occurs (e.g. workflow actions not available)
353
     */
354
    public function deleteAction(Request $request, RouteEntity $route)
355
    {
356
        return $this->deleteInternal($request, $route, false);
357
    }
358
359
    /**
360
     * This method includes the common implementation code for adminDelete() and delete().
361
     */
362
    protected function deleteInternal(Request $request, RouteEntity $route, $isAdmin = false)
363
    {
364
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
0 ignored issues
show
Unused Code introduced by
$controllerHelper 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...
365
366
        // parameter specifying which type of objects we are treating
367
        $objectType = 'route';
368
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_DELETE;
369
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', '::', $permLevel)) {
370
            throw new AccessDeniedException();
371
        }
372
        $logger = $this->get('logger');
373
        $logArgs = ['app' => 'ZikulaRoutesModule', 'user' => $this->get('zikula_users_module.current_user')->get('uname'), 'entity' => 'route', 'id' => $route->createCompositeIdentifier()];
374
        
375
        $route->initWorkflow();
376
        
377
        // determine available workflow actions
378
        $workflowHelper = $this->get('zikula_routes_module.workflow_helper');
379
        $actions = $workflowHelper->getActionsForObject($route);
380
        if (false === $actions || !is_array($actions)) {
381
            $this->addFlash('error', $this->__('Error! Could not determine workflow actions.'));
382
            $logger->error('{app}: User {user} tried to delete the {entity} with id {id}, but failed to determine available workflow actions.', $logArgs);
383
            throw new \RuntimeException($this->__('Error! Could not determine workflow actions.'));
384
        }
385
        
386
        if ($isAdmin) {
387
            // redirect to the list of routes
388
            $redirectRoute = 'zikularoutesmodule_route_' . ($isAdmin ? 'admin' : '') . 'view';
389
        } else {
390
            // redirect to the list of routes
391
            $redirectRoute = 'zikularoutesmodule_route_' . ($isAdmin ? 'admin' : '') . 'view';
392
        }
393
        
394
        // check whether deletion is allowed
395
        $deleteActionId = 'delete';
396
        $deleteAllowed = false;
397
        foreach ($actions as $actionId => $action) {
398
            if ($actionId != $deleteActionId) {
399
                continue;
400
            }
401
            $deleteAllowed = true;
402
            break;
403
        }
404
        if (!$deleteAllowed) {
405
            $this->addFlash('error', $this->__('Error! It is not allowed to delete this route.'));
406
            $logger->error('{app}: User {user} tried to delete the {entity} with id {id}, but this action was not allowed.', $logArgs);
407
408
            return $this->redirectToRoute($redirectRoute);
409
        }
410
        
411
        $form = $this->createForm('Zikula\RoutesModule\Form\DeleteEntityType', $route);
412
        
413
        if ($form->handleRequest($request)->isValid()) {
414
            if ($form->get('delete')->isClicked()) {
0 ignored issues
show
Bug introduced by
The method isClicked() does not seem to exist on object<Symfony\Component\Form\Form>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
415
                // execute the workflow action
416
                $success = $workflowHelper->executeAction($route, $deleteActionId);
417
                if ($success) {
418
                    $this->addFlash('status', $this->__('Done! Item deleted.'));
419
                    $logger->notice('{app}: User {user} deleted the {entity} with id {id}.', $logArgs);
420
                }
421
422
                return $this->redirectToRoute($redirectRoute);
423
            } elseif ($form->get('cancel')->isClicked()) {
0 ignored issues
show
Bug introduced by
The method isClicked() does not seem to exist on object<Symfony\Component\Form\Form>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
424
                $this->addFlash('status', $this->__('Operation cancelled.'));
425
426
                return $this->redirectToRoute($redirectRoute);
427
            }
428
        }
429
        
430
        $templateParameters = [
431
            'routeArea' => $isAdmin ? 'admin' : '',
432
            'deleteForm' => $form->createView(),
433
            $objectType => $route
434
        ];
435
        
436
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
437
        $templateParameters = $controllerHelper->processDeleteActionParameters($objectType, $templateParameters);
438
        
439
        // fetch and return the appropriate template
440
        return $this->get('zikula_routes_module.view_helper')->processTemplate($objectType, 'delete', $templateParameters);
441
    }
442
    /**
443
     * This is a custom action in the admin area.
444
     *
445
     * @param Request $request Current request instance
446
     *
447
     * @return Response Output
448
     *
449
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
450
     */
451
    public function adminReloadAction(Request $request)
452
    {
453
        return $this->reloadInternal($request, true);
454
    }
455
456
    /**
457
     * This is a custom action.
458
     *
459
     * @param Request $request Current request instance
460
     *
461
     * @return Response Output
462
     *
463
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
464
     */
465
    public function reloadAction(Request $request)
466
    {
467
        return $this->reloadInternal($request, false);
468
    }
469
470
    /**
471
     * This method includes the common implementation code for adminReload() and reload().
472
     */
473 View Code Duplication
    protected function reloadInternal(Request $request, $isAdmin = false)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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...
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...
474
    {
475
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
0 ignored issues
show
Unused Code introduced by
$controllerHelper 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...
476
477
        // parameter specifying which type of objects we are treating
478
        $objectType = 'route';
479
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_OVERVIEW;
480
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', '::', $permLevel)) {
481
            throw new AccessDeniedException();
482
        }
483
        /** TODO: custom logic */
484
485
        $templateParameters = [
486
            'routeArea' => $isAdmin ? 'admin' : ''
487
        ];
488
489
        // return template
490
        return $this->render('@ZikulaRoutesModule/Route/reload.html.twig', $templateParameters);
491
    }
492
    /**
493
     * This is a custom action in the admin area.
494
     *
495
     * @param Request $request Current request instance
496
     *
497
     * @return Response Output
498
     *
499
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
500
     */
501
    public function adminRenewAction(Request $request)
502
    {
503
        return $this->renewInternal($request, true);
504
    }
505
506
    /**
507
     * This is a custom action.
508
     *
509
     * @param Request $request Current request instance
510
     *
511
     * @return Response Output
512
     *
513
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
514
     */
515
    public function renewAction(Request $request)
516
    {
517
        return $this->renewInternal($request, false);
518
    }
519
520
    /**
521
     * This method includes the common implementation code for adminRenew() and renew().
522
     */
523 View Code Duplication
    protected function renewInternal(Request $request, $isAdmin = false)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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...
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...
524
    {
525
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
0 ignored issues
show
Unused Code introduced by
$controllerHelper 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...
526
527
        // parameter specifying which type of objects we are treating
528
        $objectType = 'route';
529
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_OVERVIEW;
530
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', '::', $permLevel)) {
531
            throw new AccessDeniedException();
532
        }
533
        /** TODO: custom logic */
534
535
        $templateParameters = [
536
            'routeArea' => $isAdmin ? 'admin' : ''
537
        ];
538
539
        // return template
540
        return $this->render('@ZikulaRoutesModule/Route/renew.html.twig', $templateParameters);
541
    }
542
543
    /**
544
     * Process status changes for multiple items.
545
     *
546
     * This function processes the items selected in the admin view page.
547
     * Multiple items may have their state changed or be deleted.
548
     *
549
     * @param Request $request Current request instance
550
     *
551
     * @return bool true on sucess, false on failure
552
     *
553
     * @throws RuntimeException Thrown if executing the workflow action fails
554
     */
555
    public function adminHandleSelectedEntriesAction(Request $request)
556
    {
557
        return $this->handleSelectedEntriesActionInternal($request, true);
558
    }
559
    /**
560
     * Process status changes for multiple items.
561
     *
562
     * This function processes the items selected in the admin view page.
563
     * Multiple items may have their state changed or be deleted.
564
     *
565
     * @param Request $request Current request instance
566
     *
567
     * @return bool true on sucess, false on failure
568
     *
569
     * @throws RuntimeException Thrown if executing the workflow action fails
570
     */
571
    public function handleSelectedEntriesAction(Request $request)
572
    {
573
        return $this->handleSelectedEntriesActionInternal($request, false);
574
    }
575
576
    /**
577
     * This method includes the common implementation code for adminHandleSelectedEntriesAction() and handleSelectedEntriesAction().
578
     */
579
    protected function handleSelectedEntriesActionInternal(Request $request, $isAdmin = false)
580
    {
581
        $objectType = 'route';
582
583
        // Get parameters
584
        $action = $request->request->get('action', null);
585
        $items = $request->request->get('items', null);
586
587
        $action = strtolower($action);
588
        
589
        $selectionHelper = $this->get('zikula_routes_module.selection_helper');
590
        $workflowHelper = $this->get('zikula_routes_module.workflow_helper');
591
        $logger = $this->get('logger');
592
        $userName = $this->get('zikula_users_module.current_user')->get('uname');
593
594
        // process each item
595
        foreach ($items as $itemid) {
596
            // check if item exists, and get record instance
597
            $entity = $selectionHelper->getEntity($objectType, $itemid, false);
598
            if (null === $entity) {
599
                continue;
600
            }
601
            $entity->initWorkflow();
602
603
            // check if $action can be applied to this entity (may depend on it's current workflow state)
604
            $allowedActions = $workflowHelper->getActionsForObject($entity);
605
            $actionIds = array_keys($allowedActions);
606
            if (!in_array($action, $actionIds)) {
607
                // action not allowed, skip this object
608
                continue;
609
            }
610
611
            $success = false;
612
            try {
613
                if ($action != 'delete' && !$entity->validate()) {
614
                    continue;
615
                }
616
                // execute the workflow action
617
                $success = $workflowHelper->executeAction($entity, $action);
618
            } catch(\Exception $e) {
619
                $this->addFlash('error', $this->__f('Sorry, but an error occured during the %s action.', ['%s' => $action]) . '  ' . $e->getMessage());
620
                $logger->error('{app}: User {user} tried to execute the {action} workflow action for the {entity} with id {id}, but failed. Error details: {errorMessage}.', ['app' => 'ZikulaRoutesModule', 'user' => $userName, 'action' => $action, 'entity' => 'route', 'id' => $itemid, 'errorMessage' => $e->getMessage()]);
621
            }
622
623
            if (!$success) {
624
                continue;
625
            }
626
627
            if ($action == 'delete') {
628
                $this->addFlash('status', $this->__('Done! Item deleted.'));
629
                $logger->notice('{app}: User {user} deleted the {entity} with id {id}.', ['app' => 'ZikulaRoutesModule', 'user' => $userName, 'entity' => 'route', 'id' => $itemid]);
630
            } else {
631
                $this->addFlash('status', $this->__('Done! Item updated.'));
632
                $logger->notice('{app}: User {user} executed the {action} workflow action for the {entity} with id {id}.', ['app' => 'ZikulaRoutesModule', 'user' => $userName, 'action' => $action, 'entity' => 'route', 'id' => $itemid]);
633
            }
634
        }
635
636
        return $this->redirectToRoute('zikularoutesmodule_route_' . ($isAdmin ? 'admin' : '') . 'index');
637
    }
638
}
639